Heikki Turunen
Heikki Turunen

Reputation: 11

Search value from JSON Array

I have simple question from JSON Array.

my JSON Object is :

[
    {
        "id":"1bc4aa42-1ef9-11e7-b023-97a5ff9c3a97",
        "name":"DFB-572",
        "imei":13226005525791,
        "vehicle_params":{
            "vin":null,
            "make":null,
            "model":null,
            "plate_number":null
        }
    },
    {
        "id":"1bc6b4f4-1ef9-11e7-b6fd-7fb7b5ac771a",
        "name":"DFB-575",
        "imei":13226008595395,
        "vehicle_params":{
            "vin":null,
            "make":null,
            "model":null,
            "plate_number":null
        }
    }
]

I need to find the "id" of the object with "name" field with value "DFB-572". I have to find this value from a JSONarray or ArrayList, and it should return value of "id" (so "1bc4aa42-1ef9-11e7-b023-97a5ff9c3a97").

Can somebody show me example?

My code is:

HttpResponse<String> paluuREST = AbaXapi.HttpResponse(abaxString);
String x = paluuREST.getBody();

JSONObject obj = new JSONObject(x);
JSONArray body = obj.getJSONArray("id");
System.out.println(body);

ArrayList<Object> objects = new ArrayList<>();
for (Object o : body) {
    objects.add(o);
}

System.out.println("objects = " + objects);
Object getFirst = objects.get(0);

Upvotes: 0

Views: 1044

Answers (1)

code_mechanic
code_mechanic

Reputation: 1148

You could do something like this

JSONArray arr = new JSONArray(x);

for(int i = 0; i < arr.length(); i++) {
    JSONObject obj = arr.getJSONObject(i);

    if("DFB-572".equals(obj.getString("name")) {
        return obj.getString("id");
    }
}

But you have to be sure, that this structure remains the same and the type of value doesn't change.

Explore docs for more useful methods.

Upvotes: 1

Related Questions