我有 json,我正在尝试使用 Jackson 解析它。 JSON 看起来像 -
coupons: {
1: {
title: "Mode von",
description: "",
type: "offer",
code: "-",
expiry: "0000-00-00",
link: ""
},
2: {
title: "Prime 1",
description: "",
type: "offer",
code: "-",
expiry: "0000-00-00",
link: "http://test.com/"
}
}
这里的优惠券数量并不是恒定的,并且会根据响应的不同而有所不同。 我的困境是创建相应的java类来保存这样的对象。
我尝试将 map 用作 -
public class Coupons {
Map<String, String>coupons = new HashMap<String, String>();
public Map<String, String> getCoupons() {
return coupons;
}
}
但是-
System.out.println(coupons.getCoupons().get("type"));
System.out.println(coupons.getCoupons().get("code"));
总是让我为空。对于这个 json 来说,什么是正确的 java 类?
最佳答案
您的第一级键是索引号 1、2、3 等。 因此,为了获取类型和代码,您必须指定 key 。
你可以这样做:
var coupons = coupons.getCoupons(); //<--breakpoint to see if this is really populated.
foreach( String key in coupons.Keys ){ //<- pseudo code, iterate over keys
var obj = coupons.get(key);
var type = obj.get("type");
etc..
}
希望这可以帮助您继续前进
关于java - 解析动态 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10161559/