Json数组到对象列表

时间:2014-09-20 12:21:12

标签: java json web-services rest glassfish

我有一个JAX-RS休息服务。然后我在Netbeans中调用此服务。我使用的是genson-1.0。 我这样称呼服务:

    ArrayList<Appointment> appointments;
    AppointmentRRSClient client = new AppointmentRRSClient();        
    Object response = client.allAppointments(Appointment.class); 

我的JSON数组

[{"id":1,"date":"2014-09-19","patient_id":1,"patient_name":"Lorenzana, Jerome Keith G.","patient_mobile":"+639178374407","staff_id":1,"staff_name":"Tugado, John Ephraim G.","location":"Makati Health Center","type":"walk-in","remarks":"okay lang"},{"id":2,"date":"2014-09-19","patient_id":2,"patient_name":"Black, Gucci G.","patient_mobile":"+639178488120","staff_id":1,"staff_name":"Tugado, John Ephraim G.","location":"Makati Health Center","type":"walk-in","remarks":"okay lang"},{"id":3,"date":"2014-09-19","patient_id":3,"patient_name":"Sagucio, Matthew V.","patient_mobile":"+6391068753242","staff_id":1,"staff_name":"Tugado, John Ephraim G.","location":"Makati Health Center","type":"walk-in","remarks":"okay lang"},{"id":4,"date":"2014-09-19","patient_id":4,"patient_name":"Lizardo, Daniel Z.","patient_mobile":"+639175606349","staff_id":1,"staff_name":"Tugado, John Ephraim G.","location":"Makati Health Center","type":"walk-in","remarks":"okay lang"},{"id":5,"date":"2014-09-19","patient_id":5,"patient_name":"Abulencia, Chester X.","patient_mobile":"+639051200480","staff_id":1,"staff_name":"Tugado, John Ephraim G.","location":"Makati Health Center","type":"walk-in","remarks":"okay lang"}]

错误

  

线程中的异常&#34; main&#34; javax.ws.rs.WebApplicationException:HTTP   500内部服务器错误   com.owlike.genson.ext.jaxrs.GensonJsonConverter.readFrom(GensonJsonConverter.java:127)     在   org.glassfish.jersey.message.internal.ReaderInterceptorExecutor $ TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:188)     在   org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:134)     在   org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:988)     在   org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:833)     在   org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:768)     在   org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:96)     在   org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:740)     在   org.glassfish.jersey.client.JerseyInvocation.access $ 500(JerseyInvocation.java:88)     在   org.glassfish.jersey.client.JerseyInvocation $ 2.call(JerseyInvocation.java:650)     在org.glassfish.jersey.internal.Errors.process(Errors.java:315)at   org.glassfish.jersey.internal.Errors.process(Errors.java:297)at   org.glassfish.jersey.internal.Errors.process(Errors.java:228)at   org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:421)     在   org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:646)     在   org.glassfish.jersey.client.JerseyInvocation $ Builder.method(JerseyInvocation.java:375)     在   org.glassfish.jersey.client.JerseyInvocation $ Builder.get(JerseyInvocation.java:275)     在   myPackage.AppointmentRRSClient.allAppointments(AppointmentRRSClient.java:39)     在   mPackage.AppointmentRRSClientTest.main(AppointmentRRSClientTest.java:25)   引起:com.owlike.genson.JsonBindingException:不能   反序列化以输入类myPackage.Appointment at   com.owlike.genson.Genson.deserialize(Genson.java:391)at   com.owlike.genson.ext.jaxrs.GensonJsonConverter.readFrom(GensonJsonConverter.java:125)     ... 18更多引起:com.owlike.genson.stream.JsonStreamException:   预期第0行和第0列的非法字符{但请阅读&#39; [&#39; !在   com.owlike.genson.stream.JsonReader.newWrongTokenException(JsonReader.java:949)     在com.owlike.genson.stream.JsonReader.begin(JsonReader.java:425)at   com.owlike.genson.stream.JsonReader.beginObject(JsonReader.java:157)     在   com.owlike.genson.reflect.BeanDescriptor._deserWithCtrArgs(BeanDescriptor.java:120)     在   com.owlike.genson.reflect.BeanDescriptor.deserialize(BeanDescriptor.java:95)     在   com.owlike.genson.convert.BeanViewConverter.deserialize(BeanViewConverter.java:102)     在   com.owlike.genson.convert.NullConverter $ NullConverterWrapper.deserialize(NullConverter.java:56)     在com.owlike.genson.Genson.deserialize(Genson.java:389)... 19更多   Java结果:1建立成功(总时间:1秒)

我的JSON格式是否错误?

Illegal character at row 0 and column 0 expected { but read '['

当我获取单个数据时,工作正常。

{"username":null,"password":null,"staff_id":1,"staff_name":"Tugado, John Ephraim G.","staff_gender":"male","staff_position_id":1,"health_center_id":1,"health_center_name":"Makati Health Center","account_type":"administrator","account_id":1,"staff_position":"Doctor"}

提前致谢!

修改

AppointmentRRSClient有这个方法来获取json数据并将其解析为Appointments类型的对象列表。

public <T> T allAppointments(Class<T> responseType) throws ClientErrorException {
        WebTarget resource = webTarget;
        resource = resource.path("allAppointments");
        return resource.request(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
    }

解决方案

我使用了Gson。现在我这样称呼服务。

List<String> names = new ArrayList<String>();

        URL url = new URL("http://my-url.com/rest/name");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));
                String response = "";
        String output;
        while ((output = br.readLine()) != null) {
            response += output;
        }
                conn.disconnect();
               // System.out.println(response);
        Gson gson = new Gson();
                TypeToken<List<String>> token = new TypeToken<List<String>>(){};
                names = gson.fromJson(response, token.getType());

2 个答案:

答案 0 :(得分:1)

您的json包含一个apointments数组,但您要反序列化为约会对象。带子串的解决方案可能适用于这种情况,但它不干净也不稳定(如果要反序列化具有多个元素的列表会发生什么 - 你得到第一个......),你不应该这样做这样做。

干净的解决方案是更改方法签名:

public <T> T allAppointments(Class<T> responseType)

public <T> T allAppointments(GenericType<T> responseType) {
  WebTarget resource = webTarget;
  resource = resource.path("allAppointments");
  return resource.request(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
}

然后你这样称呼它:

AppointmentRRSClient client = new AppointmentRRSClient();        
List<Appointment> response = client.allAppointments(new GenericType<List<Appointment>>(){}); 

备注 GenericType不是来自Genson但来自泽西岛的那个:javax.ws.rs.core.GenericType

答案 1 :(得分:-1)

如错误所示,预计会{,但会找到[

如果JSON尚未转换为字符串,则转换为myJson.substring(1, myJson.length() -1)并尝试再次解析它,它应该可以正常工作。