내 응용 프로그램은 json 형식으로 특정 유형의 배열을 생성하는 웹 서비스를 사용해야합니다.json String을 java List로 변환하는 방법?
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();
}
}
그런 다음, 내 클라이언트에서,이 같은 소비 것 : 이는 방법입니다 JSON 문자열이 제대로 검색됩니다
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);
하지만 배열로 변환 할 때 나는 다음과 같은 오류가 발생합니다 :
{"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
내가 뭘 잘못하고 있니?
저지 클라이언트를 사용하고 그 위에 GSON을 레이어링하는 것을 볼 수 있습니다. 이것이 의도적 인 것인지 확실하지 않지만 JSON과 JAXB 주석의 통합은 매우 좋습니다. 저지 클라이언트는 자동으로 응답을 구문 분석하여 개체를 반환 할 수 있습니다. 그것은 당신의 코드를 조금 더 단순하게 만들 것입니다. –