[英]JSON Parsing Array then Objects in Java
我是JSON
新手,如果有人可以帮助我解析它,将不胜感激。
就像先解析数组然后解析对象,然后解析属性数组中的内容一样。
有什么建议可以从哪里开始?
这段代码是我获取json文件的方式
String json = IOUtils.toString(response.getEntity().getContent());
System.out.println(json);
显示的是我需要解析的样本。 我需要以下信息:
"name":"",
"attributeName": "Alternate Name",
"attributeValue": "",
"attributeName": "Functional Area",
"attributeValue": "N/A"
[
{
"id": 1234,
"name": "",
"formId": 34,
"sortOrder": 0,
"attributes": [
{
"id": 67899,
"attribute": {
"attributeName": "Alternate Name",
"attributeType": "Text",
"id": 894
},
"attributeValue": ""
},
{
"id": 67185,
"attribute": {
"attributeName": "Description",
"attributeType": "TextArea",
"id": 900
},
"attributeValue": ""
},
{
"id": 11345,
"attribute": {
"attributeName": "Functional Area",
"attributeType": "DropdownList",
"id": 902,
"values": [
{
"id": 3471,
"sortOrder": 0,
"attributeValue": "N/A"
},
{
"id": 3472,
"sortOrder": 1,
"attributeValue": "ES"
},
{
"id": 3473,
"sortOrder": 2,
"attributeValue": "IPC"
},
{
"id": 3474,
"sortOrder": 3,
"attributeValue": "ISS"
},
{
"id": 3475,
"sortOrder": 4,
"attributeValue": "TECH"
}
]
},
"attributeValue": "N/A"
]
然后还有另一个数组(类似于上面的数组)需要解析。 用相同的方式解析它是一个巨大的文件。
先感谢您
使用Maven中都可用的Jackson或Gson之类的工具。
例如,使用杰克逊:
MyData data = new ObjectMapper().reader(MyData.class).readValue(response.getEntity().getContent());
data.getName(); // "name":""
data.getAttributes().get(0).getAttribute().getName(); // "attributeName": "Alternate Name"
data.getAttributes().get(0).getAttribute().getValue(); // "attributeValue": "",
data.getAttributes().get(2).getAttribute().getName(); // "attributeName": "Functional Area"
data.getAttributes().get(2).getAttribute().getValue(); // "attributeValue": "N/A",
// If you want to get fancy
data.getAttribute("Alternate Name").getValue();
data.getAttribute("Functional Area").getValue();
为此,您需要以下映射类。 您可以反序列化为Map
,然后使用get
和cast进行挖掘,但是我更喜欢具有适当方法和类型的Java对象。 @JsonIgnoreProperties
批注允许您仅映射您关心的JSON字段。
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyData {
@JsonProperty
private String name;
@JsonProperty
private List<Attribute> attributes;
public String getName() {
return name;
}
public List<Attribute> getAttributes() {
return attributes;
}
// If you want to get fancy
public AttributeSpec getAttribute(String name) {
for(Attribute attr : attributes) {
if(name.equals(attr.getName())) {
return attr;
}
}
throw new IllegalArgumentException("Unknown name " + name);
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class Attribute {
@JsonProperty
private AttributeSpec attribute;
public AttributeSpec getAttribute() {
return attribute;
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class AttributeSpec {
@JsonProperty
private String attributeName;
@JsonProperty
private String attributeValue;
public String getName() {
return attributeName;
}
public String getValue() {
return attributeValue;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.