【问题标题】:accessing nested list in JSONArray访问 JSONArray 中的嵌套列表
【发布时间】:2020-10-31 03:38:58
【问题描述】:

我从原始 JSON 字符串创建了一个 JSONObject。然后我从它创建了一个JSONArray。我正在尝试访问JSONArray 的每个索引的"location" 列表,因为我需要"location" 构造函数的"location" 信息。

这是我目前所拥有的

try
{
    //create a JSON Object with the raw string
    JSONObject json=new JSONObject(responseData);
    //create array of businesses
    JSONArray arr=json.getJSONArray("businesses");
    for(int i=0;i<arr.length();i++)
    {
        //I need "location" info here
        locations.add(new Location(arr.getJSONObject(i).getString("id"),arr.getJSONObject(i).getString("name"), arr.getJSONObject(i).getString("image_url"),"placeholder",0));
    }
}
catch (JSONException e)
{
    e.printStackTrace();
}

【问题讨论】:

    标签: java json android-studio


    【解决方案1】:

    好吧,我的答案很明显,但不知何故我让自己复杂化了。这对我有用。

    for(int i=0;i<arr.length();i++)
    {
        JSONObject loc=arr.getJSONObject(i).getJSONObject("location");
        locations.add(new Location(arr.getJSONObject(i).getString("id"), arr.getJSONObject(i).getString("name"), arr.getJSONObject(i).getString("image_url"),loc.getString("address1")+" "+ loc.getString("address2")+","+loc.getString("city")+","+loc.getString("zip_code"),0));
    }
    

    【讨论】:

    • 尝试使用更快的array.map()操作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多