How to get the value of json child in an array

廉价感情. 提交于 2020-03-05 00:23:52

问题


How can the value of bio and the value of link in this JSON file to a string i am using android studio

{
  "Amber": [
    {
      "Info": {
        "name": "Amber",
        "bio": "Turkish-Cypriot",
        "image": "null"
      },
      "Class": {
        "Adorable": {
          "name": "",
          "link": ""
        },
        "IronAge": {
          "name": "",
          "link": ""
        }
      }
    }
  ]
}

my java code

    private void parseResult_GetWebData(String result) {
        try {
            JSONObject response = new JSONObject(result);
            JSONArray jsonArray = response.getJSONArray("Amber");

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.optJSONObject(i);
                JSONObject jsonArray1 = jsonObject.getJSONObject("Info");
                JSONObject jsonArray2 = jsonObject.getJSONObject("Class");

                    String bio = jsonArray1.optString("bio");
                    String link = jsonArray2.optString("link");



            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

With my code am not getting any result, i don,t know what exactly am doing work


回答1:


You should use data model i.e standard way.

Main Pojo class

public class MyModel
{
    private Amber[] Amber;

    public Amber[] getAmber ()
    {
        return Amber;
    }

    public void setAmber (Amber[] Amber)
    {
        this.Amber = Amber;
    }

    @Override
    public String toString()
    {
        return "[Amber = "+Amber+"]";
    }
}

Amber.java

public class Amber
{
    private Class Class;

    private Info Info;

    //Can not getClass name of this method becuase getClass method is define in Object class so make it just getClassi or anything else.
    public Class getClassi ()
    {
        return Class;
    }

    public void setClass (Class Class)
    {
        this.Class = Class;
    }

    public Info getInfo ()
    {
        return Info;
    }

    public void setInfo (Info Info)
    {
        this.Info = Info;
    }

    @Override
    public String toString()
    {
        return "Amber [Class = "+Class+", Info = "+Info+"]";
    }
}

Class.java

public class Class
{
    private Adorable Adorable;

    private IronAge IronAge;

    public Adorable getAdorable ()
    {
        return Adorable;
    }

    public void setAdorable (Adorable Adorable)
    {
        this.Adorable = Adorable;
    }

    public IronAge getIronAge ()
    {
        return IronAge;
    }

    public void setIronAge (IronAge IronAge)
    {
        this.IronAge = IronAge;
    }

    @Override
    public String toString()
    {
        return "Info [Adorable = "+Adorable+", IronAge = "+IronAge+"]";
    }
}

IronAge.java

public class IronAge
{
    private String name;

    private String link;

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public String getLink ()
    {
        return link;
    }

    public void setLink (String link)
    {
        this.link = link;
    }

    @Override
    public String toString()
    {
        return "IronAge [name = "+name+", link = "+link+"]";
    }
}

Adorable.java


public class Adorable
{
    private String name;

    private String link;

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public String getLink ()
    {
        return link;
    }

    public void setLink (String link)
    {
        this.link = link;
    }

    @Override
    public String toString()
    {
        return "Adorable [name = "+name+", link = "+link+"]";
    }
}

Info.java

public class Info
{
    private String image;

    private String name;

    private String bio;

    public String getImage ()
    {
        return image;
    }

    public void setImage (String image)
    {
        this.image = image;
    }

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public String getBio ()
    {
        return bio;
    }

    public void setBio (String bio)
    {
        this.bio = bio;
    }

    @Override
    public String toString()
    {
        return " class [image = "+image+", name = "+name+", bio = "+bio+"]";
    }
}

Now use GSON to parse JSON data to model class.

This is the Gradle dependency for GSON

dependencies {
  implementation 'com.google.code.gson:gson:2.8.6'
}
public void parse(String jsonString){
        Gson gson = new Gson();
        MyModel model = gson.fromJson(jsonString, MyModel.class);
        for(Amber amber : model.getAmber()){
            //TO GET Links
            String link1 = amber.getClassi().getAdorable().getLink();
            String link2 = amber.getClassi().getIronAge().getLink(); 
        }
    }


You can use this to convert JSON to model pojo classes.




回答2:


The Class is JSOnObject with multiple JSONObject's inside, so once after getting Class you need to iterate through each JSONObject to get the link value

JSONObject jsonObject2 = jsonObject.getJSONObject("Class");
Iterator<String> itr = jsonObject2.keys();

while(itr.hasNext())  {

     JSONObject innerObj = jsonObject2.getJSONObject(itr.next());
     String link = innerObj.optString("link");
   }



回答3:


Please check the updated response of the above code. In my system, I successfully executed the code without crash and value output.

.

        try {
            String json= "{\n" +
                    "  \"Amber\": [\n" +
                    "    {\n" +
                    "      \"Info\": {\n" +
                    "        \"name\": \"Amber\",\n" +
                    "        \"bio\": \"Turkish-Cypriot\",\n" +
                    "        \"image\": \"null\"\n" +
                    "      },\n" +
                    "      \"Class\": {\n" +
                    "        \"Adorable\": {\n" +
                    "          \"name\": \"\",\n" +
                    "          \"link\": \"\"\n" +
                    "        },\n" +
                    "        \"IronAge\": {\n" +
                    "          \"name\": \"\",\n" +
                    "          \"link\": \"\"\n" +
                    "        }\n" +
                    "      }\n" +
                    "    }\n" +
                    "  ]\n" +
                    "}";
            JSONObject jsonObject = new JSONObject(json);
            JSONArray jsonArrayAmber= jsonObject.getJSONArray("Amber");
            for(int i=0; i<jsonArrayAmber.length(); i++) {
                JSONObject jsonObject1= jsonArrayAmber.getJSONObject(i).getJSONObject("Info");
                if(jsonObject1!=null) {
                    String bioValue= jsonObject1.getString("bio");
                    System.out.println("jsonTest "+bioValue);
                }
                JSONObject jsonObject2= jsonArrayAmber.getJSONObject(i).getJSONObject("Class");
                if(jsonObject2!=null) {
                    JSONObject jsonObjectAdorable = jsonObject2.getJSONObject("Adorable");
                    if(jsonObjectAdorable!=null) {
                        String linkAdorable = jsonObjectAdorable.getString("link");
                        System.out.println("jsonTest "+linkAdorable);
                    }
                    JSONObject jsonObjectIronAge = jsonObject2.getJSONObject("IronAge");
                    if(jsonObjectIronAge!=null) {
                        String IronAgeLink = jsonObjectIronAge.getString("link");
                        System.out.println("jsonTest "+ IronAgeLink);
                    }
                }
            }
    } catch (Exception e){
        e.printStackTrace();
    }



回答4:


Because some field names in your JSON string are not fixed, a better way is to covert it to a Map<String, Object> and retrieve value hierarchically as following code snippet.

BTW, there two identical field name - link - in JSON string, so I modify its value for identification as follows:

Modified JSON string

...
"Adorable": {
  "name": "",
  "link": "Adorable-link"
},
"IronAge": {
  "name": "",
  "link": "IronAge-link"
}
...

Code snippet

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> data = mapper.readValue(jsonStr, new TypeReference<HashMap<String, Object>>(){});

data.forEach((k,v) -> {
    ((List<Object>) v).forEach(e -> {
        Map<String, Object> infoNode = (Map<String, Object>) ((Map<String, Object>) e).get("Info");
        System.out.println("The value of bio: " + infoNode.get("bio").toString());

        Map<String, Object> classNode = (Map<String, Object>) ((Map<String, Object>) e).get("Class");
        classNode.forEach((k1,v1) -> {
            System.out.println("The value of link in " + k1 + ": " + ((Map<String, Object>) v1).get("link").toString());
        });
    });
});

Console output

The value of bio: Turkish-Cypriot
The value of link in Adorable: Adorable-link
The value of link in IronAge: IronAge-link




回答5:


Simple and short answer, please try this one

 try {
        JSONObject objects=new JSONObject(object);
        JSONArray array=objects.getJSONArray("Amber");
        for(int j=0; j<array.length(); j++)
        {
            String bio=array.optJSONObject(j).optJSONObject("Info").optString("bio");
            String linkClass=array.optJSONObject(j).optJSONObject("Class").optJSONObject("Adorable").optString("link");
            String linkIronAge=array.optJSONObject(j).optJSONObject("Class").optJSONObject("IronAge").optString("link");
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }


来源:https://stackoverflow.com/questions/59816857/how-to-get-the-value-of-json-child-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!