您的位置:首页 > Web前端 > JavaScript

FastJSON

2016-08-11 17:19 579 查看

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格式的数据
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  FastJSON