Json简单解析与生成实例
package com.example.yulongji.android4;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
private Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/*
* 方式一
*
*
* */
public void onclick1(View view) {
parseJson();
parseJsons();
}
/*
单条数据生成与解析
{"person":{"id":1,"address":"北京","age":23,"name":"张三"}}
*/
private void parseJson() {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", 1);
jsonObject.put("name", "张三");
jsonObject.put("address", "北京");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("person", jsonObject);
System.out.println(jsonObject1);
//{"person":{"id":1,"address":"北京","age":23,"name":"张三"}}
person = new Person();
JSONObject jObject = new JSONObject(jsonObject1.toString()).getJSONObject("person");
person.setId(Integer.parseInt(jObject.getString("id")));
person.setName(jObject.getString("name"));
person.setAddress(jObject.getString("address"));
System.out.println(person);
} catch (JSONException e) {
e.printStackTrace();
}
}
/*
多条数据
{"persons":{"person3":"Person{address='南昌', id=3, name='王五'}",
"person1":"Person{address='北京', id=1, name='张三'}",
"person2":"Person{address='上海', id=2, name='李四'}"
}
}
*/
public void parseJsons() {
try {
JSONObject jsonObject = new JSONObject();
JSONObject jsOb = new JSONObject();
Person person1 = new Person(1, "张三", "北京");
Person person2 = new Person(2, "李四", "上海");
Person person3 = new Person(3, "王五", "南昌");
jsonObject.put("person1", person1);
jsonObject.put("person2", person2);
jsonObject.put("person3", person3);
jsOb.put("persons", jsonObject);
System.out.println(jsOb);
/*
{"persons":{"person3":"Person{address='南昌', id=3, name='王五'}",
"person1":"Person{address='北京', id=1, name='张三'}",
"person2":"Person{address='上海', id=2, name='李四'}"
}
}
*/
JSONArray jarray = new JSONArray();
jarray.put(0, "张三");
jarray.put(1, "上海");
jarray.put(2, "南昌");
JSONObject js = new JSONObject();
js.put("array", jarray);
System.out.println(js);
//{"array":["张三","上海","南昌"]}
//解析array
JSONObject jsonob = new JSONObject(js.toString());
JSONArray jsona = jsonob.getJSONArray("array");
String string1 = jsona.getString(0);
String string2 = jsona.getString(1);
String string3 = jsona.getString(2);
System.out.println(string1 + ":" + string2 + ":" + string3);
//张三:上海:南昌
} catch (JSONException e) {
e.printStackTrace();
}
}
}