Receive json array value for string - Java

Asked

Viewed 654 times

1

Hello,

I don’t have so much knowledge in Json and I’m having a problem and I couldn’t find an exact solution to it in the community.

I have the following json file format:

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

  },

What I need and can’t get:

Take the 'prodType' value inside the 'Alternate' 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 didn’t declare 'Type' and 'Element' because I don’t know if I should and how I would.

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

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

Does anyone know how to proceed?

Grateful!

1 answer

2


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

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 field alternate 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 Meusdata class (or another name you give it) to:

public class MeusDados {
    public String name;
    public String description;
    public Alternate alternate;
}
  • Perfect! That’s what I was doing wrong. I had already seen some examples somewhat similar but had not understood very well, thank you, you broke a branch!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.