Json常用操作

时间:2022-01-09 06:11:31

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<WebServiceConfig> 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);