Home > database >  How can I get names from different JSON objects in a JSON Array for example
How can I get names from different JSON objects in a JSON Array for example

Time:10-06

{
 item:[
     {
      item_id: 1
      add_on:[
             {
             name: Thin Crust
             },

             {
             name: Extra Cheese
             },
             
             {
             name: Extra Sauce
             }

     }]
}

I want to get these names and place them into one TextView

CodePudding user response:

First of all include the JSON Library in your project.

Then access your JSON Object like this:

JSONObject jsonObject = new JSONObject(jsonString); // here is your JSON as String

// Get your Json Array of item

JSONArray itemArray = jsonObject.getJSONArray("item");

// Get your first Element from your array 

JSONObject firstItem = itemArray.getJSONObject(0);

// Then get your add_on array

JSONArray itemArray = firstItem.getJSONArray("add_on");

// After you get your array Get your second object which is { name: Extra Cheese}

JSONObject secondObject = itemArray.getJSONObject(1);

// Then you get your itemName this way:

String itemName = secondObject.getString("name");

CodePudding user response:

First of all you need to correct to JSON input. It's not valid JSON. Correct JSON should be :

{
    "item": [{
        "item_id": 1,
        "add_on": [{
                "name": "Thin Crust"
            },

            {
                "name": "Extra Cheese"
            },

            {
                "name": "Extra Sauce"
            }
        ]
    }]
}

After that with Jackon library you can get the data from Json in POJO as below:

POJO(s):

class Items {

  @JsonProperty("item")
  public List<Item> item;
}

class Item {

  @JsonProperty("item_id")
  public int itemId;

  @JsonProperty("add_on")
  public List<Name> addOn;
}

class Name {

  @JsonProperty("name")
  public String name;
}

Conversion with Jackson:

public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
    String json = "{\r\n"   
        "  \"item\": [{\r\n"   
        "    \"item_id\": 1,\r\n"   
        "    \"add_on\": [{\r\n"   
        "        \"name\": \"Thin Crust\"\r\n"   
        "      },\r\n"   
        "\r\n"   
        "      {\r\n"   
        "        \"name\": \"Extra Cheese\"\r\n"   
        "      },\r\n"   
        "\r\n"   
        "      {\r\n"   
        "        \"name\": \"Extra Sauce\"\r\n"   
        "      }\r\n"   
        "    ]\r\n"   
        "  }]\r\n"   
        "}";
    
    Items item = (new ObjectMapper()).readValue(json, Items.class);
    System.out.println(item);

  }

Now from this object structure you can get names.

  • Related