你好,游客 登录 注册 搜索
背景:
阅读新闻

JSON XML IO数据操作

[日期:2013-07-20] 来源:Linux社区  作者:hjw541988478 [字体:大 中 小]

二、JSON解析

主要是通过JsonWriter类和JsonReader类实现读写功能。

JsonWriter----------具体的写操作如下代码:

writer.beginObject();
 writer.name("id").value(product.id);<STRONG>//key-value对应</STRONG>
 writer.name("name").value(product.name);
 writer.endObject();

一般来说,我们要尽可能的分层次的解析,让代码实现更好的分离,流操作-数组操作-对象操作。

JsonReader--------具体的读操作:

reader.beginObject();
  while (reader.hasNext())
  {
   String field = reader.nextName();//游标往后移

     
   if (field.equals("id"))
   {
    id = reader.nextString();//获取数据
   }
   else if (field.equals("name"))
   {
    name = reader.nextString();

   }
   else
   {
    reader.skipValue();
   }
  }
  reader.endObject();

一般来说,只要Reader初始化输入流,通过ArrayList接收,分层次的读取便可实现功能。

JSON XML IO数据操作

三、IO操作

和JavaIO操作类似。分为字节流和字符流,推荐用字节流。

写文件:

public void onClick_SaveImageToSDCard(View view)
 {
  try
  {
   FileOutputStream fos = new FileOutputStream(
     Android.os.Environment.getExternalStorageDirectory()
       + "/image.jpg");<STRONG>//获取sd卡根目录</STRONG>
   InputStream is = getResources().getAssets().open("image.jpg");

   byte[] buffer = new byte[8192];
   int count = 0;
   while ((count = is.read(buffer)) >= 0)
   {
    fos.write(buffer, 0, count);<STRONG>//写文件</STRONG>
   }
   fos.close();
   is.close();
   Toast.makeText(this, "已成功将图像文件写到SD卡上.", Toast.LENGTH_LONG).show();
  }
  catch (Exception e)
  {
   Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
  }
 }

读文件:

public void onClick_ReadImageFromSDCard(View view)
 {
  String filename = android.os.Environment.getExternalStorageDirectory()
    + "/image.jpg";
 
  if (!new File(filename).exists())
  {
   Toast.makeText(this, "还没有往SD卡写入图像文件", Toast.LENGTH_LONG).show();
   return;
  }
  ImageView imageView = (ImageView) findViewById(R.id.imageview);
  try
  {
   FileInputStream fis = new FileInputStream(filename);<STRONG>//初始化文件输入流</STRONG>
   Bitmap bitmap = BitmapFactory.decodeStream(fis);
   imageView.setImageBitmap(bitmap);

   fis.close();
  }
  catch (Exception e)
  {
   
  }
 }

JSON XML IO数据操作

如果不用数据库的话,以上操作都能实现数据操作,不过更推荐xml文件读写,当然如果在网络应用中,用JSON是最好的轻量级选择。

更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11

linux
相关资讯       JSON XML 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款