Gson,FastJson,JackJson,ProtoBuf 數據格式轉換詳解

一、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());

二、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);

三、JackJson

依賴
implementation 'com.fasterxml.jackson.core:jackson-databind:2.11.0'

須要 throws JsonProcessingException java

private static ObjectMapper MAPPER = new ObjectMapper();git

實體類(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)

四、ProtoBuf

配置依賴 具體配置查看 demogithub

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();
}

本文源碼 FormatConversionExamplejson

相關文章
相關標籤/搜索