- 生成json数据
public String toJson() {
String result = "";
Person person1 = new Person(10, "john", "scnu");
JSONObject jsonObject = new JSONObject();// 总对象
JSONArray jsonarray = new JSONArray();// 子对象数组
JSONObject jsonPerson1 = new JSONObject();// 子对象
try {
jsonPerson1.put("age", person1.getAge());
jsonPerson1.put("name", person1.getName());
jsonPerson1.put("school", person1.getSchool());
jsonarray.put(jsonPerson1);
jsonObject.put("Person", jsonarray);
result = jsonObject.toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
返回的result就是json格式的数据。
2.如何解析
public String Jsonto(){
Person person = new Person();// 用于保存json解析出来的数据
String result = "";
String json = toJson();
try {
JSONObject jsonObject =new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("Person");
JSONObject object =jsonArray.getJSONObject(0);
person.setAge(object.getInt("age"));
person.setName(object.getString("name"));
person.setSchool(object.getString("school"));
result = "age:"+person.getAge()+" name:"+ person.getName()+" school:"+person.getSchool();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
3.总结
JSONObject 对象相当于一个json格式里面的一个{},而JSONArray 相当于json格式里面的一个[].
具体的解析方法要根据当前的json的格式来进行解析。