Get json array value for string - Java

1

Hello,

I do not have much knowledge in Json and I have a problem and I did not find an exact solution of it in the community.

I have the following format in the json file:

     {
    "name" : "ProductName",
    "description" : "description",
    "alternate": [
      {"type": "prodType", "element": "prodElement"}
    ]

  },

What I need and can not do:

Take the 'prodType' value inside the string and store it in a string and do the same with the 'prodElement' value.

My Gson file looks like this:

  @SerializedName("name")
    public String name;

  @SerializedName("description")
    public String description;

  @SerializedName("alternate")
    public List alternate;

I did not declare 'Type' and 'Element' because I do not know if I should and how I would.

I made the getters and setters, but it only returns the entire line:

{"type": "prodType", "element": "prodElement"}

Does anyone know how to proceed?

Thank you!

    
asked by anonymous 19.10.2016 / 01:00

1 answer

2

Your definition of the object is wrong. Alternate is a collection of objects with two fields: "type" and "element". The following class definition represents the json data reported:

public class MeusDados {
    public String name;
    public String description;
    public List<Alternate> alternate;
}

public class Alternate {
    public String type;
    public String element;
}

You can test with the code below:

String json = "{\"name\":\"ProductName\",\"description\":\"description\",\"alternate\":[{\"type\":\"prodType\",\"element\":\"prodElement\"}]}";

Gson gson = new Gson();
MeusDados dados = gson.fromJson(json, MeusDados.class);
if (dados.alternate.get(0).element.equals("prodElement")) {
    // entrará aqui!!!
}

The first element of List "alternate" contains the data you want to inspect. Note that if you have access to the routine that generates this json and this alternate field is not an array, but always a single object, modify your json to:

{
    "name" : "ProductName",
    "description" : "description",
    "alternate": {
        "type": "prodType", 
        "element": "prodElement"
    }
},

And change the definition of the class MyData (or any other name given to it) to:

public class MeusDados {
    public String name;
    public String description;
    public Alternate alternate;
}
    
19.10.2016 / 01:43