1

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(JerseyInvocation.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.GensonJsonConverter.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());

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I posted the solution I found. I don't really get it. I'm doing java for 2 months now and it's much more difficult than .NET
-1

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.

3 Comments

I edited my post so you can see how it fetches the json from my rest service. I don't know what to do to convert the json to string. Any ideas?
I managed to solve my problem using gson since it accepts the json format from my rest service.
@JohnEphraimTugado your statement sounds strange, by default no json lib would accept to deserialize an array to an object. Some provide an option to accept it, but gson doesn't. I don't see how it could work with Gson (or another lib) without any changes to your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.