Json转化的三种方式


1. Gson

1.添加依赖

<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.2.4</version>
</dependency>

2.转化方法

①.对象转Json:

Gson gson = new Gson();
String json = gson.toJson(Object object);

.Json转对象:

gson.fromJson(String json, Class<T> classOfT)

③.集合转Json: 

Gson gson = new Gson();
String json = gson.toJson(Object object);

④.Json转集合:

TypeToken<T> typeOfT = new TypeToken<T>(){};
T fromJson = (T)gson.fromJson(json, typeOfT.getType());

2. Json-lib

1.添加依赖

<dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
        <classifier>jdk15</classifier>
</dependency>

2.转化方法

.对象转Json: 

JSONObject fromObject = JSONObject.fromObject(Object object);
String string = fromObject.toString();

.Json转对象:

JSONObject fromObject2 = JSONObject.fromObject(string);
Object bean =JSONObject.toBean(JSONObject jsonObject, Class beanClass)

.集合转Json:

JSONArray fromObject = JSONArray.fromObject(Object object);
String string = fromObject.toString();

④.Json转集合:

JSONArray fromObject2 = JSONArray.fromObject(string);
Collection collection = JSONArray.toCollection 
(JSONArray jsonArray, Class objectClass)

3. Fastjson

Fastjson是阿里巴巴公司开发的Java语言编写的JSON的处理器

1.添加依赖

<dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.31</version>
</dependency>

2.转化方法

①.对象转Json: JSON.toJSONString(Object object);

.Json转对象: JSON.parseObject(String text,Class<T> Class);

③.集合转Json: JSON.toJSONString(Object object)

④.Json转集合: JSON.parseArray(String text,Class<T> Class);

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2020 CODEPRJ.COM