黑猴子的家:JavaWeb 之 Json 的Java常用转换方式

1、Gson

1)添加依赖

    com.google.code.gson
    gson
    2.2.4

2)转化方法

(1)对象转Json

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

(2)Json转对象

gson.fromJson(String json, Class classOfT) 

(3)集合转Json

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

(4)Json转集合

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

2、Json-Lib

1)添加依赖

    net.sf.json-lib
    json-lib
    2.4
    jdk15

2)转化方法

(1)对象转Json

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

(2)Json转对象

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

(3)集合转Json

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

(4)Json转集合

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

3、Fastjson

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

1)添加依赖

    com.alibaba
    fastjson
    1.2.31

2)转化方法

(1)对象转Json

JSON.toJSONString(Object object);

(2)Json转对象

JSON.parseObject(String text,Class Class);

(3)集合转Json

JSON.toJSONString(Object object)

(4)Json转集合

JSON.parseArray(String text,Class Class);

4、Jackson

1)添加依赖

    com.fasterxml.jackson.core
    jackson-databind
    2.8.8

2)转换方法
public static String object_to_json(Object object) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(object);
}

public static  T json_to_object(String json, Class mainClass, Class... parametricClasses) throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    JavaType parametricType = mapper.getTypeFactory().constructParametricType(mainClass, parametricClasses);
    T readValue = mapper.readValue(json, parametricType);
    return readValue;
}

你可能感兴趣的:(黑猴子的家:JavaWeb 之 Json 的Java常用转换方式)