Android中Json数据的生成与解析

  1. 生成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的格式来进行解析。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值