sam
sam

Reputation: 1243

get field list from json object list with Jackson

I have JSON data that is getting from api, I want to get list of a field inside of json data.

JSON data :

    [  
       {  
          "code":"en",
          "native":true,
          "plurals":{  
             "length":2,
             "forms":[  
                "one",
                "other"
             ]
          }
       }, {  
          "code":"de",
          "native":true,
          "plurals":{  
             "length":2,
             "forms":[  
                "one",
                "other"
             ]
          }
       }, {  
          "code":"le",
          "native":true,
          "plurals":{  
             "length":2,
             "forms":[  
                "one",
                "other"
             ]
          }
       }
]

I want to get code fields data as list<String> like below :

["en","de","le"]

what is the easiest way to do this?

Note : I am using Spring's RestTemplate to get data.

Upvotes: 1

Views: 3909

Answers (2)

Use the findValues method to extract the value of all properties named "code":

ObjectMapper om = new ObjectMapper();
JsonNode tree = om.readTree(json);

List<JsonNode> code = tree.findValues("code");

Running it on your example data gives the result

["en", "de", "le"]

Upvotes: 1

Alien
Alien

Reputation: 15878

Try below method.

public static void main(String[] args) throws JSONException {
        String jsonString  = jsonResponseFromApi;

        JSONObject obj= new JSONObject();
        JSONObject jsonObject = obj.fromObject(jsonString);

        ArrayList<String> list = new ArrayList<String>();

        for(int i=0; i<jsonObject.length(); i++){
            list.add(jsonObject.getJSONObject(i).getString("code"));
        }

        System.out.println(list);
    }   
    }

Refer below thread for more details How to Parse this JSON Response in JAVA

Upvotes: 0

Related Questions