FastJson 字符串转JAVA对象 (父对象包含子对象的 json 串)

 

1. json字符串转对象

附:JSON 转 Map  -->  Map<String,String> map = (Map<String,String>)JSON.parse(panResult);

package A;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import pojo.Child;
import pojo.Preant;

public class A {

	public static void main(String[] args) {
		String str = "{\"name\":\"jack\",\"age\":\"20\",\"ch\":{\"name\":\"sum\",\"age\":\"10\"}}";
		Preant p =JSON.parseObject(str, new TypeReference<Preant>() {});
		System.out.println(p.getName());
		Child ch =p.getCh();
		System.out.println(ch.getAge());
	}
	
}
@Data
public class Preant {

	String name;
	int age;
	Child ch;
}
@Data
public class Child {
	String name;
	int age;
	
}

2.JSONArray 字符串 转对象的两种方式(fastjson)

原字符串:

[{"callAnswerTime":1512961620000,"result":"成功","platformNo":"201710109999","callEndTime":1512961676000,"phone":"13651731502","callStartTime":1512961600000,"resultCode":0,"templateCode":"TM0","batchId":8740,"loanUsername":"姓名"},{"callAnswerTime":1512961562000,"result":"成功","platformNo":"201710109999","callEndTime":1512961592000,"phone":"13651731502","callStartTime":1512961524000,"resultCode":0,"templateCode":"TM0","batchId":8740,"loanUsername":"姓名"},{"callAnswerTime":1512961200000,"result":"成功","platformNo":"201712110000280302","jobId":"20171122001","callEndTime":1512961230000,"phone":"13651731502","callStartTime":1512961185000,"resultCode":0,"templateCode":"TM0","batchId":8740,"loanUsername":"姓名"}]

代码:

方式一、JSONArray arr = JSONArray.parseArray(batchResult);
方式二、 List<BatchResult> parseArray = JSON.parseArray(batchResult, BatchResult.class);

 

3.JSONArray 转对象误区

 

解析是会报错出现异常:Exception is :com.alibaba.fastjson.JSONException: syntax error, expect [, actual string, pos 0

修改如下:JSON.toJSONString(req.getParameter("batchResult")) 这一行去掉了JSON.toJSONString,转出来的json格式正常,可以正常运行,所以JSON.toJSONString 要慎用

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值