FastJSON

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格式的数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值