简体   繁体   中英

Json array to a list of object

I have a JAX-RS Rest Service. I then call this service in Netbeans. I'm using genson-1.0. I call the service like this:

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

My JSON Array

[{"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"}]

Error

Exception in thread "main" javax.ws.rs.WebApplicationException: HTTP 500 Internal Server Error at com.owlike.genson.ext.jaxrs.GensonJsonConverter.readFrom(GensonJsonConverter.java:127) at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:188) at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:134) at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:988) at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:833) at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:768) at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:96) at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:740) at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocat ion.java:88) at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:650) at 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) at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:646) at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:375) at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:275) at myPackage.AppointmentRRSClient.allAppointments(AppointmentRRSClient.java:39) at mPackage.AppointmentRRSClientTest.main(AppointmentRRSClientTest.java:25) Caused by: com.owlike.genson.JsonBindingException: Could not deserialize to type class myPackage.Appointment at com.owlike.genson.Genson.deserialize(Genson.java:391) at com.owlike.genson.ext.jaxrs.GensonJson Converter.readFrom(GensonJsonConverter.java:125) ... 18 more Caused by: com.owlike.genson.stream.JsonStreamException: Illegal character at row 0 and column 0 expected { but read '[' ! at com.owlike.genson.stream.JsonReader.newWrongTokenException(JsonReader.java:949) at com.owlike.genson.stream.JsonReader.begin(JsonReader.java:425) at com.owlike.genson.stream.JsonReader.beginObject(JsonReader.java:157) at com.owlike.genson.reflect.BeanDescriptor._deserWithCtrArgs(BeanDescriptor.java:120) at com.owlike.genson.reflect.BeanDescriptor.deserialize(BeanDescriptor.java:95) at com.owlike.genson.convert.BeanViewConverter.deserialize(BeanViewConverter.java:102) at com.owlike.genson.convert.NullConverter$NullConverterWrapper.deserialize(NullConverter.java:56) at com.owlike.genson.Genson.deserialize(Genson.java:389) ... 19 more Java Result: 1 BUILD SUCCESSFUL (total time: 1 second)

Is my JSON in a bad format?

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

When I fetch single data things work fine.

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

Thanks in advance!

EDIT:

The AppointmentRRSClient has this method to get the json data and parse it as list of object of type 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);
    }

Solution

I used Gson . Now I call the service like this.

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

Your json contains an array of apointments but you are deserializing to an appointment object. The solution with substring maybe works for this case, but it is not clean nor stable (what happens if you want to deserialize a list that has more than one element - you get the first one...), you shouldn't do it this way.

The clean solution would be to change the method signature from:

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

to

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

And then you call it this way:

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

Remark GenericType is not the one from Genson but from Jersey: javax.ws.rs.core.GenericType

As the error say, an { is expected but [ was found.

Convert your JSON to a String if it is not already, then myJson.substring(1, myJson.length() -1) and try to parse it again, it should works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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