User user = new User();
user.setGrade("1班");
user.setId(1);
user.setName("zs");
User user2 = new User();
user2.setGrade("2班");
user2.setId(2);
user2.setName("ls");
//新建数组
List list = new ArrayList();
list.add(user);
list.add(user2);
String s1 = JSON.toJSONString(user);
System.out.println(s1);
输出:
{"grade":"1班","id":1,"name":"zs"}
JSONObject jsonObject = JSONObject.parseObject(s1);
Object id = jsonObject.get("id"); //拿到id
System.out.println(id);//1
System.out.println("json对象转json字符串 "+jsonObject.toJSONString());
输出:
json对象转json字符串 {"grade":"1班","name":"zs","id":1}
1
User user1 = JSON.parseObject(s1, User.class);
System.out.println(user1.getName());
输出:
zs
List users = JSONArray.parseArray(s1, User.class);
users.forEach(obj-> System.out.println(obj.toString()));
输出:
com.alibaba.fastJson.User@762efe5d
com.alibaba.fastJson.User@5d22bbb7
Object toJSON = JSON.toJSON(list);
System.out.println("list-->jsonStr"+toJSON);
输出:
list转json字符串[{"grade":"1班","id":1,"name":"zs"},{"grade":"2班","id":2,"name":"ls"}]
String str = "{\"1\":\"zs\",\"2\":\"ls\",\"4\":\" ww\",\"5\":\"ml\"}";
//第一种
Map maps = (Map) JSON.parse(str);
System.out.println("第1种");
for (Object obj : maps.keySet()) {
System.out.println("key:" + obj + "value:" + maps.get(obj));
}
//第二种
Map mapTypes = JSON.parseObject(str);
System.out.println("第2种");
for (Object obj : mapTypes.keySet()) {
System.out.println("key:" + obj + "value:" + mapTypes.get(obj));
}
//第三种
Map mapType = JSON.parseObject(str, Map.class);
System.out.println("第3种");
for (Object obj : mapType.keySet()) {
System.out.println("key:" + obj + "value:" + mapTypes.get(obj));
}
//第四种
/**
* JSONObject是Map接口的一个实现类
*/
Map json = (Map) JSONObject.parse(str);
//第五种
Map jsonMap = (Map) JSONObject.parseObject(str);
输出:
第1种
key:1value:zs
key:2value:ls
key:4value: ww
key:5value:ml
第2种
key:1value:zs
key:2value:ls
key:4value: ww
key:5value:ml
第3种
key:1value:zs
key:2value:ls
key:4value: ww
key:5value:ml