Json常用操作

本文介绍了如何使用Java进行JSON字符串的解析与对象转换,包括获取属性值、反序列化、对象转换等核心操作,并提供了详细的代码示例。

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

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值