您的位置:首页 > 移动开发 > Android开发

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

2017-08-07 16:14 579 查看

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"}]


基本都是类似。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android json