Android下的JSON解析有很多的方法,今天学习其中的两种,第一种是轻量级,也就是数据量比较容易解析的,第二种是重量级一点的,也就是数据量比较多,而且解析比较复杂的。
在学习这两种方法之前,首先先学习如何生成JsonObject对象
生成Json数据的完整代码如下:
package com.yupeibiao.jsondeom;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button mButton;
private Intent mIntent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
writeMessage(createJsonObject());
intiViews();
initEvents();
}
public void initEvents(){
mButton.setOnClickListener(this);
}
public void intiViews(){
mButton=new Button(this);
}
public void writeMessage(JSONObject message){
String filePath=Environment.getExternalStorageDirectory() + File.separator + "linmeini&yupeibiao"
+ File.separator + "love.txt";
File file=new File(filePath);
//如果文件目录不存在,就创建目录
if(!file.exists()){
file.getParentFile().mkdirs();
}
BufferedWriter bw=null;
try {
bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(message.toString());
Toast.makeText(MainActivity.this,"文件写入完毕",Toast.LENGTH_SHORT);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(bw!=null){
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* JSON对象记录信息
* @return
*/
public JSONObject createJsonObject(){
JSONObject message=new JSONObject();
try{
JSONArray telephone=new JSONArray();
//先写入名字
message.put("name","yupeibiao&linmeini");
//同过JSONArray可以存储更多的细节信息 将信息用对象封装起来
telephone.put("188****9764");
telephone.put("155****4715");
message.put("电话", telephone);
//写入时长
JSONArray loveTime=new JSONArray();
loveTime.put("2014年9月10日---------------------2015年8月20日");
message.put("时长", loveTime);
}catch(Exception e){
Toast.makeText(this, "读取失败", Toast.LENGTH_SHORT).toString();
}
return message;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
mIntent=new Intent(MainActivity.this,JSONParseDeomActivity.class);
startActivity(mIntent);
break;
default:
break;
}
}
}
从上面我们可以总结,JsonObject实际上是以key value的方式进行存放的,其中的key是String类的,而value可以是boolean,int,String,甚至是JsonObject对象。
通过不停的put的方式的方式生成Json数据。
接下来是解析Json数据。
第一种,是JsonReader,从Aandroid 3.0之后便开始增加进去的解析方式。
过程:第一步:得到JsonReader对象
第二步:开始解析Array,解析数组
第三步:解析数组中的对象
第四步:结束解析
完整代码贴出如下:
JSONParseDeomActivity
package com.example.jsondeom;
import java.io.StringReader;
import android.app.Activity;
import android.os.Bundle;
import android.util.JsonReader;
public class JSONParseDeomActivity extends Activity {
private static final String JSONString = "[{\"name\":\"yupeibiao\",\"age\":21},{\"lindear\":\"Mike\",\"age\":19}]";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
JSONReaderUtils.parseJSON(JSONString);
}
}
接下来是工具类 JSONReaderUtils
package com.example.jsondeom;
import java.io.IOException;
import java.io.StringReader;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.util.JsonReader;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public class JSONReaderUtils {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public static void parseJSON(String data) {
//得到JsonReader对象
JsonReader reader = new JsonReader(new StringReader(data));
// 开始解析
try {
//先开始读数组
reader.beginArray();
while (reader.hasNext()) {
//读对象
reader.beginObject();
while(reader.hasNext()){
String key=reader.nextName();
if(key.equals("name")){
System.out.println("name------------------------"+reader.nextString());
}else if(key.equals("age")){
System.out.println("age------------------------"+reader.nextInt());
}else{
System.out.println("JsonReader 解析完毕");
}
}
//解析Object完毕
reader.endObject();
}
reader.endArray();
} catch (IOException e) {
e.printStackTrace();
}
}
}
从网络上他人的博客得到的解析的步骤是:
先分析一下这个JSON字符串的结构:一个JSONArray里面有两个JSONObject
再分析一下JsonReader解析这个JSON字符串的流程:
遇到【[】,开始解析数组(reader.beginArray())
遇到【{】,开始解析对象(reader.beginObject())
遇到【"】,开始解析第一个键值对
遇到【"】,开始解析第二个键值对
遇到【}】,结束解析对象(reader.endObject())
遇到【{】,开始解析对象(reader.beginObject())
遇到【"】,开始解析第一个键值对
遇到【"】,开始解析第二个键值对
遇到【}】,结束解析对象(reader.endObject())
遇到【]】,结束解析数组(reader.endArray())
第二种:Gosn解析
对于比较复杂的数据使用Gosn解析会比较方便,其实主要是将需要解析的数据进行类封装,然后使用对应的class字节码文件自动完成解析的方式。
第二种方式参考http://blog.csdn.net/tkwxty/article/details/34474501 写的不错,收藏学习。