skip to Main Content
{
 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

2

Answers


  1. 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");
    
    Login or Signup to reply.
  2. 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 = "{rn" + 
            "  "item": [{rn" + 
            "    "item_id": 1,rn" + 
            "    "add_on": [{rn" + 
            "        "name": "Thin Crust"rn" + 
            "      },rn" + 
            "rn" + 
            "      {rn" + 
            "        "name": "Extra Cheese"rn" + 
            "      },rn" + 
            "rn" + 
            "      {rn" + 
            "        "name": "Extra Sauce"rn" + 
            "      }rn" + 
            "    ]rn" + 
            "  }]rn" + 
            "}";
        
        Items item = (new ObjectMapper()).readValue(json, Items.class);
        System.out.println(item);
    
      }
    

    Now from this object structure you can get names.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search