我有一个像这样的JSON字符串:
"shipping_profiles": { "563": { "name": "name", "value": "value" }, "564": { "name": "name", "value": "value" }, "565": { "name": "name", "value": "value" }, "566": { "name": "name", "value": "value" } }
现在,我将使用 Jackson 2.0进行 解析。我正在尝试List<shipping_profiles>从JSON字符串获取a 。
List<shipping_profiles>
可能吗?
您的shipping_profiles媒体资源看起来不像数组。它代表具有动态属性的对象,因此我们应将其视为对象。如果我们对属性一无所知,可以使用@JsonAnySetter注释。算法可能如下所示:
shipping_profiles
@JsonAnySetter
请参阅我的示例实现。希望它能帮助您解决问题。输入JSON:
{ "shipping_profiles":{ "563":{ "name":"name563", "value":"value563" }, "564":{ "name":"name564", "value":"value564" }, "565":{ "name":"name565", "value":"value565" }, "566":{ "name":"name566", "value":"value566" } } }
示例程序:
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonProgram { public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); File source = new File("X:/test.json"); Entity entity = mapper.readValue(source, Entity.class); ShippingProfiles shippingProfiles = entity.getShippingProfiles(); List<Map<String, String>> profileMaps = shippingProfiles.getProfiles(); List<Profile> profiles = new ArrayList<Profile>(profileMaps.size()); for (Map<String, String> item : profileMaps) { profiles.add(mapper.convertValue(item, Profile.class)); } System.out.println(profiles); } } class Entity { @JsonProperty("shipping_profiles") private ShippingProfiles shippingProfiles; public ShippingProfiles getShippingProfiles() { return shippingProfiles; } public void setShippingProfiles(ShippingProfiles shippingProfiles) { this.shippingProfiles = shippingProfiles; } } class ShippingProfiles { private List<Map<String, String>> profiles = new ArrayList<Map<String, String>>(); @JsonAnySetter public void setDynamicProperty(String name, Map<String, String> map) { profiles.add(map); } public List<Map<String, String>> getProfiles() { return profiles; } public void setProfiles(List<Map<String, String>> profiles) { this.profiles = profiles; } } class Profile { private String name; private String value; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { return "Profile [name=" + name + ", value=" + value + "]"; } }
应用上方的照片:
[Profile [name=name563, value=value563], Profile [name=name564, value=value564], Profile [name=name565, value=value565], Profile [name=name566, value=value566]]