Receive a single object of a class using JSON and parsing to java with GSON

0

I have a webService in PHP and MySQL that sends me a JSON with the data I need. The problem is that in the android activity I have always used this code to pair the JSON:

Gson gson = new Gson();
p = gson.fromJson(result, new TypeToken<List<Persona>>(){}.getType());

And that is very useful when the JSON contains several objects of the class, in this case Person, but I will always receive a single object from the Person class, so I use this code:

Gson gson = new Gson();
p = gson.fromJson(result, new TypeToken<Persona>(){}.getType());

and it gives me the following error:

  

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2

PS: if I use the first formula, it gives me the error:

  

java.util.ArrayList can not be cast

What is the correct way to manage JSONs with GSON? Thank you very much.

    
asked by midlab 05.12.2018 в 18:08
source

1 answer

0

If what you receive is just an object (instead of an array of objects) then to decode the json it would be:

Persona persona = gson.fromJson(result, Persona.class);

Note: beware that an array of a single object is still an array.

    
answered by 05.12.2018 в 19:54