[英]Parsing JSON Object with no identifier with Jackson
我从Web服务获取JSON,我得到的JSON响应是:
{
"response":"itemList",
"items":[
"0300300000",
"0522400317",
"1224200035",
"1224200037",
"1547409999"
]
}
我正在寻找项数组中的每个id。 问题是当项目数组中没有id的标识符时,我不确定如何与Jackson解析。 我的理解是我可以拥有一个带有变量id和@JsonProperty(“ id”)的项目类,但是我不知道如何进行。 我需要在列表中显示这些ID(一旦有了数据,就可以毫无问题。
有人可以指出我正确的方向。
谢谢。
您可以反序列化为类似
public class MyData {
public String response;
public List<String> items;
}
(如果您具有带有公共set
方法的私有字段,这也将起作用)。 或者,如果您不介意在数据类中包含特定于杰克逊的注释,则可以将其保留为非公开并注释它们:
public class MyData {
@JsonProperty
String response;
@JsonProperty
List<String> items;
}
无论哪种方式,都可以使用它来解析:
import com.fasterxml.jackson.databind.ObjectMapper;
//...
MyData data=new ObjectMapper().readValue(jsonStringFromWebService, MyData.class);
我想是的,您想要这样:
ArrayList<String> notifArray=new ArrayList<String>();
JSONObject jsonObj= new JSONObject (resultLine);
JSONArray jArray = jsonObj.getJSONArray("items");
for (int i = 0; i < jArray.length(); i++) {
String str = jArray.getString(i);
notifArray.add(str);
}
您可以将JSON字符串转换为JSON对象,并标识数组并获取ID。
String josn = "{\"response\":\"itemList\", \"items\":[\"0300300000\",\"0522400317\",\"1224200035\",\"1224200037\",\"1547409999\"]}";
JSONObject jsonObject = new org.json.JSONObject(josn);
JSONArray itemsArray = jsonObject.getJSONArray("items");
System.out.println("Item - 1 =" + itemsArray.getString(0));
class Something {
public String response;
@JsonCreator
public Something(@JsonProperty("response") String response) {
this.response=response;
}
public List<String> items= new ArrayList<String>();
public List<String> addItem(String item) {
items.add(item);
return items;
}
}
接着:
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String json = "{\"response\":\"itemList\",\"items\":[\"0300300000\",\"0522400317\"]}";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(json, Something.class);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.