依賴
implementation 'com.google.code.gson:gson:2.8.6'
Gson gson = new Gson();
String json = gson.toJson(new Bean());
Bean b = gson.fromJson('json',Bean.class);
gson.toJson(map)
Map<String, Object> map = gson.fromJson("json",new TypeToken<Map<String, Object>>() {}.getType());
LList<Bean> list = new ArrayList<>(); list.add(new Bean()); gson.toJson(list)
List<Bean> list = gson.fromJson('json',new TypeToken<List<Bean>>(){}.getType());
依賴
implementation 'com.alibaba:fastjson:1.2.70'
JSON.toJSONString(new Bean())
Bean b = JSON.parseObject('json',Bean.class);
JSON.toJSONString('map')
JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(new Bean())); Map<String,Object> map = (Map<String,Object>)jsonObject; Object object = map.get("array");
List<Bean> list = new ArrayList<>(); list.add(new Bean()); JSON.toJSONString(list)
JSON.parseArray('json',Bean.class);
依賴
implementation 'com.fasterxml.jackson.core:jackson-databind:2.11.0'
須要 throws JsonProcessingException java
private static ObjectMapper MAPPER = new ObjectMapper();git
MAPPER.writeValueAsString(new Bean())
MAPPER.readValue('json', Bean.class)
MAPPER.writeValueAsString('map')
Map map = MAPPER.readValue('json',Map.class);
List<Bean> list = new ArrayList<>(); list.add(new Bean()); String ljson = MAPPER.writeValueAsString(list);
MAPPER.readValue('json', ArrayList.class)
配置依賴 具體配置查看 demogithub
implementation 'com.googlecode.protobuf-java-format:protobuf-java-format:1.2'
BeanBuf beanBuf = BeanBuf.newBuilder().setName("測試").build(); String jsonFormat = JsonFormat.printToString(beanBuf);
BeanBuf bean = BeanBuf.newBuilder().build(); JsonFormat.merge('json', bean.toBuilder());
BeanBuf bean = BeanBuf.newBuilder().setAge(11111111).build(); byte[] byteArray1 = bean.toByteArray(); Arrays.toString(byteArray1)
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