JSON在传输数据时,起到了特别大的作用,因此出现了各种各样五花八门的JSON转换第三方包,在这里做一个汇总,总结一些常用的
目录
com.alibaba.fastjson
常用的API
Lsit—>JSON
JSON字符串—>List
6种json转MAP
json-lib(即net.sf.json )
常用的API
1.把java 对象列表转换为json对象数组,并转为字符串
2.把java对象转换成json对象,并转化为字符串(好像是map)
3.把JSON字符串转换为JAVA 对象数组
4.把JSON字符串转换为JAVA 对象
案例
org.json.JSONObject
构建JSONObject
直接使用 new 关键字实例化一个JSONObject对象
使用Map构建
使用JavaBean构建
解析JSONObject
com.google.gson
创建Gson对象
创建JsonObject
API
数组的序列化与反序列化
List的序列化与反序列化
对象的序列化和反序列化
com.fasterxml.jackson
com.alibaba.fastjson
可以下载第三方jar包,也可以直接建Maven项目导入依赖
https://download.csdn.net/download/qq_44709970/87607297?spm=1001.2014.3001.5503
com.alibabafastjson1.2.47
常用的API
- 对象 —> json字符串JSON.toJSONString(Object)
- json字符串—> 对象 JSON.parseObject(jsonStr,Object)
- json字符串 —> 数组 JSON.parseArray(jsonStr,T.class)
Lsit—>JSON
JSON.toJSONString(list)
JSON字符串—>List
List list = JSON.parseArray(要解析字符串,T.class);
6种json转MAP
String str = "{'0':'zhangsan','1':'lisi','2':'wangwu','3':'maliu'}";//第一种方式Map maps = (Map) JSON.parse(str);System.out.println("这个是用JSON类来解析JSON字符串!!!");for (Object map : maps.entrySet()){System.out.println(((Map.Entry)map).getKey()+" " + ((Map.Entry)map).getValue());}//第二种方式Map mapTypes = JSON.parseObject(str);System.out.println("这个是用JSON类的parseObject来解析JSON字符串!!!");for (Object obj : mapTypes.keySet()){System.out.println("key为:"+obj+"值为:"+mapTypes.get(obj));}//第三种方式Map mapType = JSON.parseObject(str,Map.class);System.out.println("这个是用JSON类,指定解析类型,来解析JSON字符串!!!");for (Object obj : mapType.keySet()){System.out.println("key为:"+obj+"值为:"+mapType.get(obj));}//第四种方式/** * JSONObject是Map接口的一个实现类 */Map json = (Map) JSONObject.parse(str);System.out.println("这个是用JSONObject类的parse方法来解析JSON字符串!!!");for (Object map : json.entrySet()){System.out.println(((Map.Entry)map).getKey()+""+((Map.Entry)map).getValue());}//第五种方式JSONObject jsonObject = JSONObject.parseObject(str);System.out.println("这个是用JSONObject的parseObject方法来解析JSON字符串!!!");for (Object map : json.entrySet()){System.out.println(((Map.Entry)map).getKey()+""+((Map.Entry)map).getValue());}//第六种方式Map mapObj = JSONObject.parseObject(str,Map.class);System.out.println("这个是用JSONObject的parseObject方法并执行返回类型来解析JSON字符串!!!");for (Object map: json.entrySet()){System.out.println(((Map.Entry)map).getKey()+""+((Map.Entry)map).getValue());}String strArr = "{{\"0\":\"zhangsan\",\"1\":\"lisi\",\"2\":\"wangwu\",\"3\":\"maliu\"}," +"{\"00\":\"zhangsan\",\"11\":\"lisi\",\"22\":\"wangwu\",\"33\":\"maliu\"}}";// JSONArray.parse()System.out.println(json);}
json-lib(即net.sf.json )
用net.sf.json包,要导入6个包来支持:
commons-beanutils-1.7.0.jar
commons-collections-3.1.jar
commons-lang-2.5.jar
commons-logging.jar
ezmorph-1.0.3.jar
json-lib-2.1-jdk15.jar
Maven依赖:
net.sf.json-libjson-lib2.4jdk15 commons-beanutilscommons-beanutils1.9.3commons-langcommons-lang2.6net.sf.ezmorphezmorph1.0.6
常用的API
import net.sf.json.JSONArray;//用于集合或数组import net.sf.json.JSONObject; //用于对象JSONObject object = new JSONObject();
1.把java 对象列表转换为json对象数组,并转为字符串
JSONArray array = JSONArray.fromObject(userlist);String jsonstr = array.toString();
2.把java对象转换成json对象,并转化为字符串(好像是map)
JSONObject object = JSONObject.fromObject(invite);String str=object.toString();
3.把JSON字符串转换为JAVA 对象数组
String personstr = getRequest().getParameter("persons");JSONArray json = JSONArray.fromObject(personstr);List persons = (List)JSONArray.toCollection(json, nvoidPerson.class);
4.把JSON字符串转换为JAVA 对象
JSONObject jsonobject = JSONObject.fromObject(str);PassportLendsEntity passportlends = null;try { //获取一个json数组 JSONArray array = jsonobject.getJSONArray("passports"); //将json数组 转换成 List泛型 List list = new ArrayList(); for (int i = 0; i < array.size(); i++) { JSONObject object = (JSONObject)array.get(i); PassPortForLendsEntity passport = (PassPortForLendsEntity)JSONObject.toBean(object, PassPortForLendsEntity.class); if(passport != null){ list.add(passport); }}
案例
public static void main(String[] args) {String jsonStr = "{\"payTime\":\"2022-11-15 11:51:39\",\"errMsg\":\"查询成功\",\"targetStatus\":\"SUCCESS\",\"totalAmount\":1,\"errCode\":\"SUCCESS\"}";//import net.sf.json.JSONObject;JSONObject netSfJson = JSONObject.fromObject(jsonStr);Map data = new HashMap();Iterator ite = netSfJson.keys();// 遍历jsonObject数据,添加到Map对象while (ite.hasNext()) {String key = ite.next().toString();String value = netSfJson.get(key).toString();data.put(key, value);}log.info("Json转Map对象之net.sf.json.JSONObject:data[{}]", data);//java序列化为jsonStudent student = Student.getStudent();JSONObject jsonObject = JSONObject.fromObject(student);//Json反序列化为java//如果对象中含有复杂对象,如List、Map或自定义javaBean,// 需要使用一下的classMap,否则转换过程中会报错Map classMap=new HashMap();classMap.put("stuObject",Student.class);student=(Student)JSONObject.toBean(jsonObject,Student.class,classMap);}
org.json.JSONObject
org.jsonjson20160810
构建JSONObject
直接使用 new 关键字实例化一个JSONObject对象
然后调用它的 put() 方法对其字段值进行设置。
JSONObject jsonObj = new JSONObject();jsonObj.put("female", true);jsonObj.put("hobbies", Arrays.asList(new String[] { "yoga", "swimming" }));jsonObj.put("discount", 9.5);jsonObj.put("age", "26");jsonObj.put("features", new HashMap() {private static final long serialVersionUID = 1L;{put("height", 175);put("weight", 70);}});System.out.println(jsonObj);
{
“features”: {
“weight”: 70,
“height”: 175
},
“hobbies”: [“yoga”, “swimming”],
“discount”: 9.5,
“female”: true,
“age”: 26
}
使用Map构建
Map map = new HashMap();map.put("female", true);map.put("hobbies", Arrays.asList(new String[] { "yoga", "swimming" }));map.put("discount", 9.5);map.put("age", "26");map.put("features", new HashMap() {private static final long serialVersionUID = 1L;{put("height", 175);put("weight", 70);}});JSONObject jsonObj = new JSONObject(map);System.out.println(jsonObj);
使用JavaBean构建
UserInfo userInfo = new UserInfo();userInfo.setFemale(true);userInfo.setHobbies(new String[] { "yoga", "swimming" });userInfo.setDiscount(9.5);userInfo.setAge(26);userInfo.setFeatures(new HashMap() {private static final long serialVersionUID = 1L;{put("height", 175);put("weight", 70);}});JSONObject jsonObj = new JSONObject(userInfo);System.out.println(jsonObj); public class UserInfo { private Boolean female;private String[] hobbies;private Double discount;private Integer age;private Map features; public Boolean getFemale() {return female;} public void setFemale(Boolean female) {this.female = female;} public String[] getHobbies() {return hobbies;} public void setHobbies(String[] hobbies) {this.hobbies = hobbies;} public Double getDiscount() {return discount;} public void setDiscount(Double discount) {this.discount = discount;} public Integer getAge() {return age;} public void setAge(Integer age) {this.age = age;} public Map getFeatures() {return features;} public void setFeatures(Map features) {this.features = features;} }
解析JSONObject
JSONObject为每一种数据类型都提供了一个getXXX(key)方法
例如:获取字符串类型的字段值就使用getString()方法,获取数组类型的字段值就使用getJSONArray()方法。
// 获取基本类型数据System.out.println("Female: " + jsonObj.getBoolean("female"));System.out.println("Discount: " + jsonObj.getDouble("discount"));System.out.println("Age: " + jsonObj.getLong("age"));// 获取JSONObject类型数据JSONObject features = jsonObj.getJSONObject("features");String[] names = JSONObject.getNames(features);System.out.println("Features: ");for (int i = 0; i < names.length; i++) {System.out.println("\t"+features.get(names[i]));} // 获取数组类型数据JSONArray hobbies = jsonObj.getJSONArray("hobbies");System.out.println("Hobbies: ");for (int i = 0; i < hobbies.length(); i++) {System.out.println("\t"+hobbies.get(i));}
com.google.gson
Gson是google提供的用来操作json数据的一个非常好用的类库 gson 在 github 上开源地址:https://github.com/google/gson
其提供了序列化和反序列化的功能。在我们进行网络开发的过程中通常会把参数封装成json格式传给后台,后台解析后的返回结果也会封装成json格式返回给调用者
如果项目中要求不要使用Fastjson,原因:Fastjson≤1.2.80的版本存在安全漏洞
序列化的前提是实现Serializable接口和序列化版本号
com.google.code.gsongson2.8.5
创建Gson对象
//第一种方式Gson gson = new Gson();//第二种方式Gson gson1 = new GsonBuilder().create();//方式二除了可以创建一个Gson对象以外还可以进行多项配置,例如,设置日期的格式化// 例如: new GsonBuilder().setDateFormat("yyyy-MM-dd");
创建JsonObject
JsonObject jsonObject = new JsonObject();jsonObject.addProperty("id", "1");//给jsonObject创建一个id属性值为1jsonObject.addProperty("bookName", "《深入Java虚拟机》");jsonObject.addProperty("bookPrice", 36.8);//打印Json字符串System.out.println(jsonObject.toString());// {"id":"1","bookName":"《深入Java虚拟机》","bookPrice":36.8}//给JsonObject添加对象JsonObject jsonObject1 = new JsonObject();jsonObject1.addProperty("chapterId", "1");jsonObject1.addProperty("chapterName", "第一章");//给JsonObject添加实体对象jsonObject.add("chapter", jsonObject1);System.out.println(jsonObject.toString());`
这里的JsonObject表示我们一样可以创建一个json对象;但是我们后面一般使用的是java对象跟json字符串的转换,可以用通过创建好的gson对象来操作
API
反序列化 toJson(对象)
序列化 fromJson(JSON字符串, 要转成的对象类型)
数组的序列化与反序列化
数组 ===>JSON字符串 toJson(arrs)
String[] str = new String[]{"《深入Java虚拟机》", "《Android插件编程》", "《OpenCV全解》"};Gson gson = new Gson();String jsonStr = gson.toJson(str);//返回一个Json字符串System.out.println(jsonStr);// ["《深入Java虚拟机》","《Android插件编程》","《OpenCV全解》"]
JSON字符串 ===>数组 fromJson(jsonStr, T)
String[] strArray = gson.fromJson(jsonStr, String[].class);for (String s : strArray) {System.out.println(s);}
List的序列化与反序列化
List集合 ===>JSON字符串 toJson(list)
List books = new ArrayList();books.add(new Book("1", "《深入Java虚拟机》"));books.add(new Book("2", "《OpenCV进阶》"));Gson gson = new Gson();String jsonListStr = gson.toJson(books);System.out.println(jsonListStr);// [{"id":"1","name":"《深入Java虚拟机》"},{"id":"2","name":"《OpenCV进阶》"}]
JSON字符串 ===>List集合 fromJson(jsonStr, T)
//获取泛型的类型Type type = new TypeToken<List>() { }.getType();//使用gson将字符串转换为泛型集合,即ListList books1 = gson.fromJson(jsonListStr, type);for (Book book : books1) {System.out.println(book.getName()); }
对象的序列化和反序列化
Gson gson = new Gson();Book book = new Book("1", "《深入Java虚拟机》");//将book类序列化成字符串String bookStr = gson.toJson(book);System.out.println(bookStr);//将bookStr反序列化成为Book类Book b = gson.fromJson(bookStr, Book.class);System.out.println(b.getName());
com.fasterxml.jackson
com.fasterxml.jackson.corejackson-core2.9.0com.fasterxml.jackson.corejackson-databind2.9.0com.fasterxml.jackson.corejackson-annotations2.9.0
import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;public class JacksonDemo {public static void main(String[] args) {String jsonString=null;try {Map jsonMap=new HashMap();ObjectMapper mapper = new ObjectMapper();Student student = Student.getStudent();jsonMap.put("param1","value1");jsonMap.put("param2","value2");jsonMap.put("student",student);jsonString= mapper.writeValueAsString(jsonMap);System.out.println("Json String");System.out.println(jsonString);} catch (JsonProcessingException e) {e.printStackTrace();}//反序列化try {ObjectMapper objectMapper = new ObjectMapper();JsonNode root = objectMapper.readTree(jsonString);Map jsonMap = objectMapper.readValue(jsonString, Map.class);System.out.println("json Object");System.out.println(jsonMap);Object student = jsonMap.get("student");System.out.println(student);System.out.println(jsonMap.get("param1"));System.out.println(jsonMap.get("param2"));System.out.println("----------------");System.out.println(root.get("student"));System.out.println(root.get("student").get("id"));System.out.println(root.get("student").get("teacher"));} catch (IOException e) {e.printStackTrace();}}}