当前位置: 代码迷 >> JavaScript >> Android中对json的解析跟处理
  详细解决方案

Android中对json的解析跟处理

热度:345   发布时间:2012-09-10 11:02:33.0
Android中对json的解析和处理
在android调用webservice时,经常要对json的格式进行处理,现在有两种方法
去处理:

1 使用JSONObject 和 JSONTokener去解析
2 使用GSON库

  先看第一种方法,假如有如下的json字符串:
{
“name”: “myName”,
“message”: ["myMessage1","myMessage2"],
“place”: “myPlace”,
“date”:  ”thisDate”
}

第一种解决方法:
  public class main extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

try {


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

String json = “{”

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

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

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

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

+ “}”;

/* Create a JSON object and parse the required values */

JSONObject object = (JSONObject) new JSONTokener(json).nextValue();

String name = object.getString(“name”);

String place = object.getString(“place”);

String date = object.getString(“date”);

JSONArray message = object.getJSONArray(“message”);

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

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

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

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

{

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

}
2 使用GSON类库
   GOOGLE提供的gson类库,地址在:
代码如下:
public class JSON_structure {
public String name;
public String place;
public String date;
public String[] message;
}

这其实是个POJO类
try {

/* Inflate TextView from the layout */

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

/* JSON data considered as an example. Generally this data is obtained

from a web service.*/

String json = “{”

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

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

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

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

+ “}”;

Gson gson = new Gson();

JSON_structure obj= 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(int i=0;i<obj.message.length;i++)

{

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

}

}

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

}


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

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

}

}