原生JSON解析
键值对的形式:键为string类型,值可以是对象也可以是数组(对象数组)。
Java自带json解析
需要自己分析Javabean
分为对象和集合两种形式
1 json对象格式字符串转换成javabean,
使用JSONObject.toBean()静态方法
String str = “{'id':110,'name':'zhangsan','sex':'male','age':18,}”;
JSONObject jsonObj = JSONObject.fromObject(str);
Student obj = (Student) JSONObject.toBean(jsonObj, Student.class);
2 Json数组格式转换成对象,使用JSONArray.toCollection()静态方法String arrStr = “[{'id':110,'name':'zhangsan','sex':'male','age':18},{'id':120,'name':'lisi','sex':'female','age':28}]”;
JSONArray array = JSONArray.fromObject(str);
Collection<?> c = JSONArray.toCollection(array, Student.class);
3 获取json对象指定属性值:
String id = jsonObj.getString("id");
4 获取jsonArray中指定的jsonObject:
JSONObject obj = array.getJSONObject(0);
6 JSONObject.toBean的时候如果转换的类中有集合
可以先定义Map<String, Class> classMap = new HashMap<String, Class>();
在classMap中put你要转换的类中的集合属性名和转换后类class: classMap.put("ts", Teacher.class);然后在toBean()的时候把参数加上:
Student student=(Student) JSONObject.toBean(str, Student.class, classMap);
二 对象转换成JSON:
1 使用JSONObject.fromObject()方法,集合对象使用JSONArray.fromObject()方法。
2 使用JSONSerializer.toJSON()方法。
GSON解析
第三方jar包
1 对简单object类型:
Gson gson = new Gson();Student s = gson.fromJson(str, Student.class);
2 json数组放入list中,使用fromJson(String, Type)方法
String u = "[{'name':'zhangsan','age':20},{'name':'zhangsan','age':20}]";
Gson g = new Gson();
Type type = new TypeToken<List<User>>(){}.getTyp );
List<User> us = g.fromJson(u, type);
二 对象转换成json字符串:
使用Gson对象的toJson()方法即可,参数是任意对象。Map<String,String> map = new HashMap<>();
map.put("name", "zs");
System.out.println(gson.toJson(map));
Fastjson解析
Fastjson API入口类是com.alibaba.fastjson.JSON,常用的序列化操作都可以在JSON类上的静态方法直接完成。
一 将json对象转换成我们需要的数据对象
1 普通object格式转换为对象
String str ="{'id':110,'name':'zhangsan','sex':'male','age':18,}";
Student s = JSON.parseObject(str, Student.class);
2 数组格式转换为集合:
String str = "[{'name':'zhangsan','age':20},{'name':'zhangsan','age':20}]";
List<Student> s = JSON.parseArray(str, Student.class);
二 对象转换为json字符串:
1 普通字符串
JSON.toJSONString(s);
2 格式字符串
//第二个参数是boolean prettyFormat属性
JSON.toJSONString(s,true);