<span style="font-size:18px;">Android中FastJson解析json1</span>
代码:
解析
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String jsonStr = getdata2();
parseData(jsonStr);
}
/**
* {"num":20,"root":[{"id":"1","name":"关羽","age":"10"},
* {"id":"2","name":"张飞","age":"20"}],
* "phone":{"p1":"p1","p2":"p2"}}
* 生成json
*/
public String getdata2(){
String objectrootStr =null;
try {
JSONObject root = new JSONObject();
JSONArray array = new JSONArray();
JSONObject object1 = new JSONObject();
object1.put("id", "1");
object1.put("name", "关羽");
object1.put("age", "10");
array.put(object1);
JSONObject object2 = new JSONObject();
object2.put("id", "2");
object2.put("name", "张飞");
object2.put("age", "20");
array.put(object2);
root.put("num", 20);
root.put("root", array);
JSONObject object=new JSONObject();
object.put("p1", "p1");
object.put("p2", "p2");
root.put("phone", object);
//生成的json字符串
objectrootStr= root.toString();
// 打印json数据
Log.e("1", "json数据"+objectrootStr);
} catch (Exception e) {
e.printStackTrace();
}
return objectrootStr;
}
/**
* {"num":20,"root":[{"id":"1","name":"关羽","age":"10"},
* {"id":"2","name":"张飞","age":"20"}],
* "phone":{"p1":"p1","p2":"p2"}}
* 对json数据进行解析
* 主要用到:
* JSON.parseArray();
* JSON.parseObject();
*
*
*/
private void parseData(String result) {
try {
// 解析num
JsonBean json = JSON.parseObject(result, JsonBean.class);
Log.e("1", json.num);
// 解析root
JSONObject object = new JSONObject(result);
Object jsonarray = object.get("root");
List<MyObj> list = JSON.parseArray(jsonarray+"", JsonBean.MyObj.class);
for (MyObj obj:list) {
Log.e("1", ""+obj.id);
}
// 解析phone
Object phone = object.get("phone");
Phone phoneStr=JSON.parseObject( phone+"", JsonBean.Phone.class);
Log.e("1", phoneStr.p1);
Log.e("1", phoneStr.p2);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
javabean
public class JsonBean {
public String num;
public List<MyObj> root;
public Phone phone;
public static class MyObj {
public String id;
public String name;
public String age;
}
public static class Phone {
public String p1;
public String p2;
}
}
源码及jar包下载
http://download.csdn.net/detail/zhaihaohao1/9477604