FastJSON
示例,解析出放入Map集合
Map parse = (Map) JSON.parse(str);
System.out.println(((List)((Map)parse.get("result")).get("future")).get(0));
示例,解析出放入对象,对象属性名要和JSON数据的key名相同。如果不相同需要加注解。
直接解析到weather对象。 此时必须有无参的构造方法才可以使用。如果没有需要在有参的构造方法上加注解,示例如下。
Weather weather = JSON.parseObject(str, Weather.class);
System.out.println(weather.getResult().getToday());
public class Weather {
private String resultcode;
private String reason;
private Result result;
private int error_code;
//如果要得到result 需要在构造方法里写上
@JSONCreator
public Weather(@JSONField(name = "resultcode") String resultcode, @JSONField(name = "reason") String reason) {
if (resultcode == null || reason == null) {
throw new RuntimeException("resultcode和 reason不能为空");
}
this.resultcode = resultcode;
this.reason = reason;
}
main方法里
构造方法里初始化数据可以得到,不初始化的得不到。
Weather weather = JSON.parseObject(str, Weather.class);
System.out.println(weather.getResult());
如果碰到JSON数据中 key值为整形1000等类似的数据无法用变量名来定义例:{ 10000:一万},那么需要这样定义,如下。
@JSONField(name = "10000")
private String text;
如果遇到数组 例如: {location:[50,100]} 解决办法如下
JSONArray可以转化为list
private int x;
private int y;
@JSONFiled(name = "location")
public void getLocation(List<Integer> location){
x = location.get(0);
y = location.get(1);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
JSON.toJSONString(weather);将对象转化为JSON格式的数据