json解析和处理

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

去处理:

1使用JSONObject和JSONTokener去解析

2使用GSON库

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

java代码:

{

“name”:“myName”,

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

“place”:“myPlace”,

“date”:”thisDate”

}

第一种解决方法:

java代码:

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+””);

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

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

for(inti=0;i<p>

{

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

}

2使用GSON类库

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

java代码:

publicclassJSON_structure{

publicStringname;

publicStringplace;

publicStringdate;

publicString[]message;

}

这其实是个POJO类

java代码:

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+””);

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

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

for(inti=0;i<p>

{

tv.append(“Message:“+obj.message+””);

}

}

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

}

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

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

}

}

相关推荐