Retrofit error when response is being parsed as list - json

I'm getting the following error when attempting to get a array of json objects using retrofit.
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 2 path $
The request is declared in the api interface as
interface HttpRequests {
#GET("/api/v1/emergency")
Observable<List<Emergency>> getEmergencies(#Query("lat") Double lat,
#Query("lng") Double lng,
#Query("dist") int dist);
Where Emergency is defined as
public class Emergency {
#SerializedName("emergencyUuid")
#Expose
private String emergencyUuid;
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lng")
#Expose
private Double lng;
#SerializedName("phoneNumber")
#Expose
private String phoneNumber;
public Emergency(){};
public Emergency(String emergencyUuid, Double lat, Double lng, String phoneNumber){
this.emergencyUuid = emergencyUuid;
this.lat = lat;
this.lng = lng;
this.phoneNumber = phoneNumber;
}
// getters & setters
}
When I replace the List<Emergency> with String I can print the response which looks somewhat like:
"[{\"emergencyUuid\":\"axkdjfiwokdfj\",\"lat\":22.22,\"lng\":33.33,\"phoneNumber\":\"12345678910\"}]"
This seems to me a perfectly fine json array with a single emergency object. I do not understand why this can't be parsed. What did I do wrong?

Related

JSON parse error: Cannot deserialize value of type `java.time.LocalDate`

Im trying to send a post to my api using postman:
But its returning an error:
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type java.time.LocalDate from String "10/11/2022": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '10/11/2022' could not be parsed at index 0;
I tried to correct do the mapping with json mapping annotation in the dto class:
#Data
#Builder
public class OfertaEspecialDTO {
private String nome;
private final double desconto_percentual;
private String descricao;
#JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
private LocalDate dataValidade;
}
But its still returning me the error.
How is the correct way to map my dateTime instance variable?
There is no issue with LocalDate instance variable mapping. Issue is with annotations used on top of class. Please refactor DTO class like this and try again.
#Setter
#Getter
public class OfertaEspecialDTO {
private String nome;
private double desconto_percentual;
private String descricao;
#JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
private LocalDate dataValidade;
}
or like this
#Data
public class OfertaEspecialDTO {
private String nome;
private double desconto_percentual;
private String descricao;
#JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
private LocalDate dataValidade;
}

convert json String to array java object by Gson

I never understand that how can I use gson.
this is my json string that is fetched from my web service:
{
"GetHistoricalNotificationsInTopicByFilterResult":[
{
"BusinessCode":"10-1-75-16-1-3-0",
"CreationDateTime":"\/Date(1502550561602)\/",
"DeviceId":"8998432005",
"Distributions":null,
"EventData":[ ],
"EventId":"com.test.revisit.events",
"EventTitle":"sending",
"Id":"69dbc367-09ws-bf3c-9re8-5c6b35ecbrtg",
"ProcessId":"4ebb6271-bf3c-9re8-a148-5c6b35ec458",
"SystemId":"com.safarayaneh.revisit",
"SystemTitle":"seeing",
"UserFullName":"jack",
"UserId":"69dbc367-32f3-4e94-bf3c-5c6b35ec3456",
"WKT":"POLYGON ((59.0 36.0, 59.01 36.01, ...))",
"WorkItemId":2354365
},{
....
}
and this is my contract class:
public class SaveNotify implements Parcelable {
private long id;
private String NotificationID;
private String MessageID;
private String CreationDateTime;
private String DeviceId;
private String UserId;
private String UserFullName;
private String SystemId;
private String SystemTitle;
private String EventId;
private String EventTitle;
private String EventData;
private String BusinessCode;
private String ProcessId;
private String WorkItemId;
private String WKT;
private String Distributions;
private String Address;
private String SaveDate;
private String Status;
private String DistributionId;
private String SchedulerCreationDateTime;
private String ExpirationDateTime;
how can I convert json string that i receive from my webservice to pojo class as array list? I want to put this list to my recycler view adapter for showing this info as a list.
What you need to create is an object that gets the field GetHistoricalNotificationsInTopicByFilterResult
public class MainObject implements Parceable{
List<SaveNotify > GetHistoricalNotificationsInTopicByFilterResult;
}
And then, with Gson parce you JSON to The MainObject
Gson gson = new Gson();
MainObject mainObject = gson.fromJson(jsonString, MainObject.class);

Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token

Currently I am working on rest service, while consuming the service getting error.
public String userName;
public String refernceNumber;
public String requestType;
public String fullName;
public String dateOfBirth;
public String placeOfBirth;
public String gender;
public String nationlaity;
public String telphoneNo;
public String mobileNo;
public String note;
public String email;
public String processId;
public List<DocumentDTO> attachmentsList;
and my documentdto is like
private String doumentNameEng;
private Integer documentId;
private String fileName;
private MultipartFile attachment;
private String ticketNo;
private String dmsRefId;
enter code here
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
at [Source: org.apache.catalina.connector.CoyoteInputStream#1171c8a3; line: 1, column: 233] (through reference chain: com.micd.process.dto.applcation["attachmentsList"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:575)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:569)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:259)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:217)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:207)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:23)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:464)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:98)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:295)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2094)
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:168)
help me to getout from this error, unable to understand this eror.

Gson parse an Object from empty string

When I use GSON deserialize a JSON String, it throws JsonSyntaxException. How can I deal with it?
{"QueueNum":1,"Result":"2","ResultMessage":"201","ReturnValue":"","TS":1448443938}
public class Response<T> {
private int Result;
private long TS;
private float ResultMessage;
private int QueueNum;
private T ReturnValue;
}

pass 2 json object rest full

#POST
#Path("create")
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.APPLICATION_JSON)
public String create(String user, CostAPIHandle apihandle,CostDataSize datasize){
String serid = "serid" + System.currentTimeMillis();
return save(user, serid, apihandle, datasize);
}
Can you show me anotation to use in this case (post a string and 2 object)
CostAPIHandle have 2 properties (float: price, int: package_size )
CostDataSize have 3 properties (float: price, int: datasize , int: dataunit)
And the string value how does it look when you post through http ?
one approach is to create a new java class with the variables that you want to use like below:
public class SomeClassName {
private String user;
private CostAPIHandle apihandle;
private CostDataSize datasize;
// getters & setters
}
and then changing your method to accept it as an input
#POST
#Path("create")
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.APPLICATION_JSON)
public String create(SomeClassName input){
String serid = "serid" + System.currentTimeMillis();
return save(input.getUser(), serid, input.getApihandle(), input.getDatasize());
}