Convert JSON to GSON object

Asked

Viewed 376 times

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 null values. Code below:

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

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

My problem is:

The class name at the beginning "Opa":{} - If I send only {"name":"Teste1234"} then it can do the conversion.

  • 1

    What language are you using? If yes see http://blog.wektabyte.com/converter-objetos-java-em-json-e-vice-versa-com-gson/

1 answer

0

when you have a json with the following structure:

`{ "Opa": {} }`

you are reporting that you own a objeto who owns a propriedade calling for 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);

Browser other questions tagged

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