APP端后端开发

Gson,FastJson,JackJson,ProtoBuf

2020-06-06  本文已影响0人  我们都很努力着

最近,后台一个接口返回了俩种不同的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<Bean> 转JSON

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

JSON转List<Bean>

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<Bean> 转JSON

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

JSON转List<Bean>

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<Bean> 转JSON

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

JSON转List<Bean>

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

上一篇下一篇

猜你喜欢

热点阅读