Mateus Viccari
Mateus Viccari

Reputation: 7709

How to convert json String to java List?

My application must consume a web service, that produces an array of specific type, in json format. This is the method:

public Unidade[] getUnidades(){
    Session s = ConnectDb.getSession();
    try {
        List<Unidade> lista = new ArrayList<Unidade>(s.createQuery("from Unidade order by unidSigla").list());
        Unidade[] unidades = lista.toArray(new Unidade[0]);
        return unidades;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        s.close();
    }
}

Then, in my client, it's consumed like this:

    WebResource webResource = client.resource("http://localhost:8080/RestauranteWeb/rest/unidades/");
    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
    String output = response.getEntity(String.class);
    System.out.println(output);
    Unidade[] unidades = new Gson().fromJson(output, Unidade[].class);
    System.out.println(unidades);

The json string is retrieved correctly, but i get the following error when converting it to array:

{"unidade":[{"unidCodigo":"17","unidSigla":"BOSTA"},{"unidCodigo":"18","unidSigla":"BOSTE"},{"unidCodigo":"13","unidSigla":"bumerangui"},{"unidCodigo":"15","unidSigla":"HHH"},{"unidCodigo":"16","unidSigla":"HHH2"},{"unidCodigo":"6","unidSigla":"papapa"},{"unidCodigo":"9","unidSigla":"pobrena"},{"unidCodigo":"7","unidSigla":"sei la"},{"unidCodigo":"3","unidSigla":"TAÇINHA"},{"unidCodigo":"5","unidSigla":"tanque"},{"unidCodigo":"1","unidSigla":"UNIDADE"},{"unidCodigo":"14","unidSigla":"zerao"}]}
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
    at com.google.gson.Gson.fromJson(Gson.java:815)
    at com.google.gson.Gson.fromJson(Gson.java:768)
    at com.google.gson.Gson.fromJson(Gson.java:717)
    at com.google.gson.Gson.fromJson(Gson.java:689)
    at br.mviccari.client.UnidadeClient.main(UnidadeClient.java:40)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
    at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:338)
    at com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:70)
    at com.google.gson.Gson.fromJson(Gson.java:803)
    ... 4 more

What am i doing wrong?

Upvotes: 0

Views: 809

Answers (1)

jtahlborn
jtahlborn

Reputation: 53694

As you can see from the data and the error, the top-level json type is an object, not an array. what you actually have is a top-level object which has an array of Unidade elements. you should define something like this for your top-level class:

public class UnidadeWrapper {
    public Unidade[] unidade;
}

Upvotes: 2

Related Questions