Convert JSON to object with GSON

1

I have a webservice ready, which returns a JSON of an object, great, working: Here is the returned JSON:

{"Opa":{"nome":"Teste1234"}}

This JSOn is of the following class:

public class Opa {
public String nome = "Basico";
}

GSON simply creates the object with the null values. Code below:

GsonBuilder etaB = new GsonBuilder();
        Gson pegador = etaB.create();
Opa teste1 = pegador.fromJson("{\"Opa\":{\"nome\":\"Teste1234\"}}",Opa.class);

I put the direct string in the fromJson method above to illustrate.

My problem is:

The name of the class at the beginning "Opa": {} - If I just send {"name": "Test1234"} then he can do the conversion.

    
asked by anonymous 16.08.2016 / 17:00

1 answer

0

When you have a json with the following structure:

'{ "Opa": {} }'

You are informing that you have a objeto that has a propriedade called Opa , and this propriedade stores another objeto .

so its structure requires two classes.:

public class Wrapper {
    public Oba Oba;
}

public class Opa {
    public String nome;
}

Finally, you can deserialize as follows:

pegador.fromJson("{\"Opa\":{\"nome\":\"Teste1234\"}}", Wrapper.class);
    
16.08.2016 / 18:03