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 要慎用