Gson,FastJson,JackJson,ProtoBuf 数据格式转换详解

最近,后台一个接口返回了俩种不同的json解析格式,就顺便整理了一下。直接上代码。文章末尾有示例demo。

1、Gson

依赖

implementation ‘com.google.code.gson:gson:2.8.6‘
Gson gson = new Gson();

实体类(Bean)转JSON

String json = gson.toJson(new Bean());

JSON转实体类(Bean)

Bean b = gson.fromJson(‘json‘,Bean.class);

Map转Json

gson.toJson(map)

Json转Map

Map<String, Object> map = gson.fromJson("json",new TypeToken<Map<String, Object>>() {}.getType());

List 转JSON

LList<Bean> list = new ArrayList<>();
list.add(new Bean());
gson.toJson(list)

JSON转List

List<Bean> list = gson.fromJson(‘json‘,new TypeToken<List<Bean>>(){}.getType());

2、FastJson

依赖

implementation ‘com.alibaba:fastjson:1.2.70‘

实体类(Bean)转JSON

JSON.toJSONString(new Bean())

JSON转实体类(Bean)

Bean b = JSON.parseObject(‘json‘,Bean.class);

Map转Json

JSON.toJSONString(‘map‘)

Json转Map

JSONObject  jsonObject = JSONObject.parseObject(JSON.toJSONString(new Bean()));
Map<String,Object> map = (Map<String,Object>)jsonObject;
Object object = map.get("array");

List 转JSON

 List<Bean> list = new ArrayList<>();
 list.add(new Bean());
 JSON.toJSONString(list)

JSON转List

JSON.parseArray(‘json‘,Bean.class);

3、JackJson

依赖

implementation ‘com.fasterxml.jackson.core:jackson-databind:2.11.0‘

需要 throws JsonProcessingException

private static ObjectMapper MAPPER = new ObjectMapper();

实体类(Bean)转JSON

MAPPER.writeValueAsString(new Bean())

JSON转实体类(Bean)

MAPPER.readValue(‘json‘, Bean.class)

Map转Json

MAPPER.writeValueAsString(‘map‘)

Json转Map

Map map = MAPPER.readValue(‘json‘,Map.class);

List 转JSON

List<Bean> list = new ArrayList<>();
list.add(new Bean()); 
String ljson = MAPPER.writeValueAsString(list);

JSON转List

MAPPER.readValue(‘json‘, ArrayList.class)

4、ProtoBuf

配置依赖 具体配置查看 demo

implementation ‘com.googlecode.protobuf-java-format:protobuf-java-format:1.2‘

ProtoBuf转Json

BeanBuf beanBuf = BeanBuf.newBuilder().setName("测试").build();
String jsonFormat = JsonFormat.printToString(beanBuf);

Json转ProtoBuf

BeanBuf bean = BeanBuf.newBuilder().build();
JsonFormat.merge(‘json‘, bean.toBuilder());

Proto序列化

BeanBuf bean = BeanBuf.newBuilder().setAge(11111111).build();
byte[] byteArray1 = bean.toByteArray();
Arrays.toString(byteArray1)

Proto反序列化

BeanBuf bean = BeanBuf.newBuilder().setAge(11111111).build();
try {
    BeanBuf buf = BeanBuf.parseFrom(bean.toByteArray());
    mBinding.textView.setText(buf.toString());
} catch (IOException e) {
	e.printStackTrace();
}

本文源码 FormatConversionExample

Gson,FastJson,JackJson,ProtoBuf 数据格式转换详解

上一篇:JQuery


下一篇:mysql 字符拼接