Android中对json的解析和处理

在android调用webservice时,经常要对json的格式进行处理,现在有两种方法

去处理:

1使用JSONObject和JSONTokener去解析

2使用GSON库

先看第一种方法,假如有如下的json字符串:

{

“name”:“myName”,

“message”:["myMessage1","myMessage2"],

“place”:“myPlace”,

“date”:”thisDate”

}

第一种解决方法:

publicclassmainextendsActivity{

@Override

publicvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

try{

TextViewtv=(TextView)findViewById(R.id.TextView01);

Stringjson=“{”

+“\”name\”:\”myName\”,”

+“\”message\”:[\"myMessage1\",\"myMessage2\"],”

+“\”place\”:\”myPlace\”,”

+“\”date\”:\”thisDate\””

+“}”;

/*CreateaJSONobjectandparsetherequiredvalues*/

JSONObjectobject=(JSONObject)newJSONTokener(json).nextValue();

Stringname=object.getString(“name”);

Stringplace=object.getString(“place”);

Stringdate=object.getString(“date”);

JSONArraymessage=object.getJSONArray(“message”);

tv.setText(“Name:“+name+”\n\n”);

tv.append(“Place:“+place+”\n\n”);

tv.append(“Date:“+date+”\n\n”);

for(inti=0;i<message.length();i++)

{

tv.append(“Message:“+message.getString(i)+”\n\n”);

}

2使用GSON类库

GOOGLE提供的gson类库,地址在:

代码如下:

publicclassJSON_structure{

publicStringname;

publicStringplace;

publicStringdate;

publicString[]message;

}

这其实是个POJO类

try{

/*InflateTextViewfromthelayout*/

TextViewtv=(TextView)findViewById(R.id.TextView01);

/*JSONdataconsideredasanexample.Generallythisdataisobtained

fromawebservice.*/

Stringjson=“{”

+“\”name\”:\”myName\”,”

+“\”message\”:[\"myMessage1\",\"myMessage2\"],”

+“\”place\”:\”myPlace\”,”

+“\”date\”:\”thisDate\””

+“}”;

Gsongson=newGson();

JSON_structureobj=gson.fromJson(json,JSON_structure.class);

tv.setText(“Name:“+obj.name+”\n\n”);

tv.append(“Place:“+obj.place+”\n\n”);

tv.append(“Date:“+obj.date+”\n\n”);

for(inti=0;i<obj.message.length;i++)

{

tv.append(“Message:“+obj.message[i]+”\n\n”);

}

}

catch(Exceptionex){ex.printStackTrace();}

}

}catch(JSONExceptione){e.printStackTrace();}

catch(Exceptionex){ex.printStackTrace();}

}

}

相关推荐