繁体   English   中英

如何将json String转换为java List?

[英]How to convert json String to java List?

我的应用程序必须使用以json格式生成特定类型数组的Web服务。 这是方法:

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();
    }
}

然后,在我的客户端,它被消耗如下:

    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);

正确检索json字符串,但在将其转换为数组时出现以下错误:

{"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

我究竟做错了什么?

从数据和错误中可以看出,顶级json类型是一个对象,而不是一个数组。 你实际拥有的是一个顶级对象,它有一个Unidade元素数组。 你应该为你的顶级类定义这样的东西:

public class UnidadeWrapper {
    public Unidade[] unidade;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM