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