JSON简单的解析单个对象方法:gson、Jackson、fastjson

json解析,其实也可以说是转换,其他的不多说了,我目前不是很清楚深层的原理,毕竟一般来说本人秉着先用后理解的方式哈,下边是简单的使用的小例子。

1、gson

jar包:

UtrRealIdentify utrRealIdentify = new UtrRealIdentify();//我自己的类
utrRealIdentify.setIsOk("this is ok");//简单的赋个值,

Gson gsonData = new GsonBuilder().create();//定义gson对象
String jsonstr = gsonData .toJson(utrRealIdentify);//为了看效果,所以我先把对象转成json,下边在转换回来,如果直接有json类型的数来直接使用的话就不用转换这步。
System.out.println(jsonstr);//{"isOk":"this is ok"}

utrRealIdentify = gsonData.fromJson(jsonstr, UtrRealIdentify.class);//解析json数据,转成java类
System.out.println(utrRealIdentify.getIsOk());//this is ok

2、 Jackson
jar包:
UtrRealIdentify utrRealIdentify =new UtrRealIdentify();

utrRealIdentify.setIsOk("this is ok");//简单的赋个值,

ObjectMapper mapper = new ObjectMapper(); // ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。 

String jsonstr = mapper.writeValueAsString(utrRealIdentify);//对象转成json
 System.out.println(jsonstr);//{"isOk":"this is ok"}
 
utrRealIdentify = mapper.readValue(jsonstr, UtrRealIdentify.class);//解析json数据,转成java类

System.out.println(utrRealIdentify.getIsOk());//this is ok


3、fastjson

jar包:

 UtrRealIdentify utrRealIdentify =new UtrRealIdentify();
 utrRealIdentify.setIsOk("this is ok");//简单的赋个值,
 
String jsonstr =JSON.toJSONString(utrRealIdentify);//对象转成json
System.out.println(jsonstr);//{"isOk":"this is ok"}
 
utrRealIdentify =JSON.parseObject(jsonstr, UtrRealIdentify.class);//解析json数据,转成java类
System.out.println(utrRealIdentify.getIsOk());//this is ok

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值