【问题标题】:How can I get names from different JSON objects in a JSON Array for example [closed]例如,如何从 JSON 数组中的不同 JSON 对象获取名称 [关闭]
【发布时间】:2021-11-26 09:14:13
【问题描述】:
{
 item:[
     {
      item_id: 1
      add_on:[
             {
             name: Thin Crust
             },

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

     }]
}

我想获取这些名称并将它们放入一个 TextView 中

【问题讨论】:

标签: java android api android-studio


【解决方案1】:

首先在您的项目中包含JSON 库。

然后像这样访问您的 JSON 对象:

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

【讨论】:

  • 我正在使用 volley request 并且我已经进入 add_on 并且我正在将结果显示到 ListView 但如果 add_on 中有多个名称,它会创建一个新的 List 实际上我需要像这样解析跟随示例:项目名称:汉堡添加:额外的奶酪,额外的酱汁,小麦面包
【解决方案2】:

首先,您需要更正 JSON 输入。它不是有效的 JSON。正确的 JSON 应该是:

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

            {
                "name": "Extra Cheese"
            },

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

使用 Jackon 库之后,您可以从 POJO 中的 Json 获取数据,如下所示:

POJO:

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

与杰克逊的转化:

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

  }

现在您可以从这个对象结构中获取名称。

【讨论】:

  • 对不起,我第一次使用 StackOverflow,所以无法正确提问,其次,我正在使用 volley 来解析所有这些我想显示的数据,例如名称:Burger Add on : sauce,奶酪、面包等
  • 我会试试这个方法,谢谢你的帮助
猜你喜欢
  • 2021-10-20
  • 2019-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多