[英]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.