博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Json常用操作
阅读量:5233 次
发布时间:2019-06-14

本文共 1543 字,大约阅读时间需要 5 分钟。

1, 获取json字符串中属性(传统方式)

import net.sf.json.JSONObject JSONObject json = JSONObject.fromObject(response); json.getString("qrcode")

2,获取json字符串中属性(面向对象方式)

import com.fasterxml.jackson.databind.ObjectMapper PaymentResponse response = new ObjectMapper().readValue(json, PaymentResponse.class);

3,从json文件中反序列化

ObjectMapper mapper = new ObjectMapper();        InputStream is = WebServiceConfig.class.getResourceAsStream("/webservice.json");TypeFactory typeFactory = mapper.getTypeFactory();CollectionType collectionType = typeFactory.constructCollectionType(List.class, WebServiceConfig.class);        List
config1 = mapper.readValue(is, collectionType);

如果不是集合对象则简单

ObjectMapper mapper = new ObjectMapper();        InputStream is = WebServiceConfig.class.getResourceAsStream("/webservice.json");WebServiceConfig config1 = mapper.readValue(is, WebServiceConfig.Class);

如果Json文件中有些属性是没有的要加上

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

 4, 把对象转换成json字符串

JSONArray.fromObject(user)

 5,把json字符串转成对象

JSONObject jsonObject = JSONObject.fromObject(json);              BaseUserInfo Address  = (BaseUserInfo) JSONObject.toBean(jsonObject, BaseUserInfo.class);

 6,对象与json互转

ObjectMapper objectMapper = new ObjectMapper();  // 将Java对象序列化为Json字符串  String objectToJson = objectMapper.writeValueAsString(initUser());  System.out.println(objectToJson);  // 将Json字符串反序列化为Java对象  User user = objectMapper.readValue(objectToJson, User.class);  System.out.println(user);

 

转载于:https://www.cnblogs.com/season2009/p/8269048.html

你可能感兴趣的文章