简体   繁体   中英

Parsing JSON Object with no identifier with Jackson

I am getting JSON from a web service, the JSON response I'm getting is:

{  
   "response":"itemList",
   "items":[  
      "0300300000",
      "0522400317",
      "1224200035",
      "1224200037",
      "1547409999"
   ]
}

I am looking to get each id within the items array. The problem is I'm unsure how to parse this with Jackson when there are no identifiers for the id in the items array. My understanding is I could have an item class with a variable id and @JsonProperty ("id"), but I don't know how to proceed. I need to display these ids in a list (which I can do no problem once I have the data.

Could someone please point me in the right direction.

Thank you.

You could deserialize into something like

public class MyData {
  public String response;
  public List<String> items;
}

(this will also work if you have private fields with public set methods). Or if you don't mind having jackson-specific annotations in your data classes, you can leave them as non-public and annotate them:

public class MyData {
  @JsonProperty
  String response;

  @JsonProperty
  List<String> items;
}

either way, use this to parse:

import com.fasterxml.jackson.databind.ObjectMapper;
//...

MyData data=new ObjectMapper().readValue(jsonStringFromWebService, MyData.class);

I think so, you want this :

    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);
    }

You can Convert the JSON String to JSON object, and identify the array and get the IDs..

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;
    }
}

and then:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM