Android中生成json格式数据的几种方法

String生成的json数据有两种

1

String json="[{'name':'tom','age':12},{'name':'jack','age':13}]";
JSONArray a = new JSONArray(json);
System.out.println(a.toString());
  •  

2

String json2="{'json':[{'name':'tom','age':14},{'name':'jack','age':15}]}";
JSONObject b= new JSONObject(json2);
System.out.println(b.toString());
  • String类型的数据加“”,然后每个key,value加单引号。

JsonObject生成的数据有两种

1

        JSONArray array =new JSONArray();
        JSONObject object =new JSONObject();
        JSONObject object1 =new JSONObject();
        JSONObject obj= new JSONObject();
        try {
            object.put("item1","value1");
            object.put("age",12);
            object.put("name","tom");
            object1.put("item2","value2");
            object1.put("age",12232);
            object1.put("name","tom");
            array.put(object);
            array.put(object1);
            obj.put("name",array);
            System.out.println(obj.toString());
        }catch (Exception e){

        }
        结果:{"name":[{"item1":"value1","name":"tom","age":12},{"item2":"value2","name":"tom","age":12232}]}
  • 2
        JSONArray array1 =new JSONArray();
        JSONObject object2 =new JSONObject();
        JSONObject object3 =new JSONObject();
        try {
            object2.put("color","red");
            object2.put("height",20);
            object3.put("color","blue");
            object3.put("height",1010);
            array1.put(object2);
            array1.put(object3);
            System.out.println(array1.toString());
        }catch (Exception e){


        }
       结果:[{"color":"red","height":20},{"color":"blue","height":1010}]
  • 将集合生成json数据

1

        Map<String ,String> map =new HashMap<>();
        Map<String ,String> map2 =new HashMap<>();
        map.put("name1","tom1");
        map.put("age1","12");
        map2.put("name1","tom1");
        map2.put("age1","12");
        JSONObject object4 =new JSONObject();
        JSONArray array2 =new JSONArray();
        array2.put(map);
        array2.put(map2);
        object4.put("key",array2);
        System.out.println(object4.toString());
        结果:{"key":[{"name1":"tom1","age1":"12"},{"name1":"tom1","age1":"12"}]}
  •  

2

        Map<String ,String> map1 =new HashMap<>();
        map1.put("as","adasd");
        map1.put("asfa","afasff");
        JSONArray array3 =new JSONArray();
        array3.put(map1);
        System.out.println(array3.toString());
        结果:[{"asfa":"afasff","as":"adasd"}]
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值