how to deserialize nested objects in java using object mapper - java

I have a sqs queue , I am polling for messages .
I get the message in following format
{
"Type" : "type_value",
"MessageId" : "message_id",
"TopicArn" : "topic_arn",
"Message" : "{\n \"contentType\": \"content_type_value\",\n \"content\": \"content_value\",\n \"eventName\": \"event_name\",\n \"eventTS\": 1591235390353\n}",
"Timestamp" : "2020-06-04T01:49:50.358Z",
"SignatureVersion" : "1",
"UnsubscribeURL" : "url"
}
when I get this body from SQS using code
String message = sqs_message_object.getBody()
Now I create a wrapper class for thie message body as following
public class SQSMessage
{
#JsonProperty("Type")
private String type;
#JsonProperty("MessageId")
private String messageId;
#JsonProperty("TopicArn")
private String topicArn;
#JsonProperty("Message")
private Message message;
#JsonProperty("Timestamp")
private String timestamp;
#JsonProperty("SignatureVersion")
private int signatureVersion;
#JsonProperty("UnsubscribeURL")
private String unSubscribeUrl;
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public String getMessageId()
{
return messageId;
}
public void setMessageId(String messageId)
{
this.messageId = messageId;
}
public String getTopicArn()
{
return topicArn;
}
public void setTopicArn(String topicArn)
{
this.topicArn = topicArn;
}
public Message getMessage()
{
return message;
}
public void setMessage(Message message)
{
this.message = message;
}
public String getTimestamp()
{
return timestamp;
}
public void setTimestamp(String timestamp)
{
this.timestamp = timestamp;
}
public int getSignatureVersion()
{
return signatureVersion;
}
public void setSignatureVersion(int signatureVersion)
{
this.signatureVersion = signatureVersion;
}
public String getUnSubscribeUrl()
{
return unSubscribeUrl;
}
public void setUnSubscribeUrl(String unSubscribeUrl)
{
this.unSubscribeUrl = unSubscribeUrl;
}
}
And I deserialize the json string in to a SQSMessage object using Object Mapper
SQSMessage sqsMessage = null;
try
{
sqsMessage = objectMapper.readValue(message,SQSMessage.class);
}
catch(JsonProcessingException e2)
{
}
all the fields are getting mapped except for Message field .
because its not just a string but another class.
public class Message
{
private String contentType;
private Content content;
private String eventName;
private Date eventTS;
public String getContentType()
{
return contentType;
}
public void setContentType(String contentType)
{
this.contentType = contentType;
}
public Content getContent()
{
return content;
}
public void setContent(Content content)
{
this.content = content;
}
public String getEventName()
{
return eventName;
}
public void setEventName(String eventName)
{
this.eventName = eventName;
}
public Date getEventTS()
{
return eventTS;
}
public void setEventTS(Date eventTS)
{
this.eventTS = eventTS;
}
}
it fils to deserialize the field Message .
how do i Map the message field to Messaeg class as mentioned.
The error I get is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `domain.Message`
(although at least one Creator exists): no String-argument constructor/factory method to deserialize
from String value ('{\n \"contentType\": \"content_type_value\",\n \"content\": \"content_value\",\n \"eventName\": \"event_name\",\n \"eventTS\": 1591235390353\n}')
at [Source: (String)"{

Related

How can I parse object inside array using retrofit

[
{
"login": "mojombo",
"id": 1,
"node_id": "MDQ6VXNlcjE=",
"avatar_url": "https://avatars0.githubusercontent.com/u/1?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/mojombo",
"html_url": "https://github.com/mojombo",
"followers_url": "https://api.github.com/users/mojombo/followers",
"following_url": "https://api.github.com/users/mojombo/following{/other_user}",
"gists_url": "https://api.github.com/users/mojombo/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mojombo/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mojombo/subscriptions",
"organizations_url": "https://api.github.com/users/mojombo/orgs",
"repos_url": "https://api.github.com/users/mojombo/repos",
"events_url": "https://api.github.com/users/mojombo/events{/privacy}",
"received_events_url": "https://api.github.com/users/mojombo/received_events",
"type": "User",
"site_admin": false
}
]
Json: https://api.github.com/users
This is URL of an API... how can i parse this object to fetch the data using retrofit?
Here is the example on how to fetch JSON object with array using retrofit. I believe you won't have troubles changing it to work with your data.
Example.java
public class Example {
#SerializedName("PnrNumber")
#Expose
private String pnrNumber;
#SerializedName("Status")
#Expose
private String status;
#SerializedName("ResponseCode")
#Expose
private String responseCode;
#SerializedName("TrainNumber")
#Expose
private String trainNumber;
#SerializedName("TrainName")
#Expose
private String trainName;
#SerializedName("JourneyClass")
#Expose
private String journeyClass;
#SerializedName("ChatPrepared")
#Expose
private String chatPrepared;
#SerializedName("From")
#Expose
private String from;
#SerializedName("To")
#Expose
private String to;
#SerializedName("JourneyDate")
#Expose
private String journeyDate;
#SerializedName("Passangers")
#Expose
private List<Passanger> passangers = null;
public String getPnrNumber() {
return pnrNumber;
}
public void setPnrNumber(String pnrNumber) {
this.pnrNumber = pnrNumber;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getResponseCode() {
return responseCode;
}
public void setResponseCode(String responseCode) {
this.responseCode = responseCode;
}
public String getTrainNumber() {
return trainNumber;
}
public void setTrainNumber(String trainNumber) {
this.trainNumber = trainNumber;
}
public String getTrainName() {
return trainName;
}
public void setTrainName(String trainName) {
this.trainName = trainName;
}
public String getJourneyClass() {
return journeyClass;
}
public void setJourneyClass(String journeyClass) {
this.journeyClass = journeyClass;
}
public String getChatPrepared() {
return chatPrepared;
}
public void setChatPrepared(String chatPrepared) {
this.chatPrepared = chatPrepared;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getJourneyDate() {
return journeyDate;
}
public void setJourneyDate(String journeyDate) {
this.journeyDate = journeyDate;
}
public List<Passanger> getPassangers() {
return passangers;
}
public void setPassangers(List<Passanger> passangers) {
this.passangers = passangers;
}
}
Passanger.Java
public class Passanger {
#SerializedName("Passenger")
#Expose
private String passenger;
#SerializedName("BookingStatus")
#Expose
private String bookingStatus;
#SerializedName("CurrentStatus")
#Expose
private String currentStatus;
public String getPassenger() {
return passenger;
}
public void setPassenger(String passenger) {
this.passenger = passenger;
}
public String getBookingStatus() {
return bookingStatus;
}
public void setBookingStatus(String bookingStatus) {
this.bookingStatus = bookingStatus;
}
public String getCurrentStatus() {
return currentStatus;
}
public void setCurrentStatus(String currentStatus) {
this.currentStatus = currentStatus;
}
}
Here are the classes which are generated from the Response which you have provided in the question.
You can use this link to generate the POJO class for JSON response.
JSON TO POJO
Add this gradle:
implementation 'com.google.code.gson:gson:2.8.2'
Init the Gson buildr:
private Gson gson;
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
gson = gsonBuilder.create();
Parse the JSON using GSON
gson.fromJson(jsonObject.getJSONObject("data").toString(), Example.class);
These are the basic steps to parse the JSON using GSON.
For more information you can refer to the below article:
Parsing JSON on Android using GSON
Or Check the GSON official GitHub Repository
GSON

how to convert string into Json and extrat from it info

I'm using retrofit2 and Rxjava2 to insert/get information from mongodb and nodeJs server, for now, I receive all data as a string but I want to get hole collection Infos from my base so I need to convert string to JSON and get each information.
My code to receive data:
1- Service:
#POST("collect/get")
#FormUrlEncoded
Observable<String> getcollection(#Field("selector") String selector);
2-RetrofitClient:
if(instance == null){
instance = new Retrofit.Builder()
.baseUrl("http://transportor.ddns.net:3000/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create()).build();
}
3- Recieve function
private void getallcollection(String selector) {
compositeDisposable.add(myServices.getcollection(selector)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<String>(){
#Override
public void accept(String s) throws Exception {
Log.d("infos",s);
}
}));
}
I'm already prepared Collection class:
public class col {
private String creator;
private String emailcol;
private String date_creation_col;
private String nom_col;
private String long_col;
private String lat_col;
private String tel_fix_col;
private String tel_mobile_col;
private String creatorcreator;
private String heure_matin_col;
private String heure_apresmatin_col;
private String type;
private String imagePath;
public col(String creator, String emailcol, String date_creation_col, String nom_col, String long_col, String lat_col, String tel_fix_col, String tel_mobile_col, String creatorcreator, String heure_matin_col, String heure_apresmatin_col, String type, String imagePath) {
this.creator = creator;
this.emailcol = emailcol;
this.date_creation_col = date_creation_col;
this.nom_col = nom_col;
this.long_col = long_col;
this.lat_col = lat_col;
this.tel_fix_col = tel_fix_col;
this.tel_mobile_col = tel_mobile_col;
this.creatorcreator = creatorcreator;
this.heure_matin_col = heure_matin_col;
this.heure_apresmatin_col = heure_apresmatin_col;
this.type = type;
this.imagePath = imagePath;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getEmailcol() {
return emailcol;
}
public void setEmailcol(String emailcol) {
this.emailcol = emailcol;
}
public String getDate_creation_col() {
return date_creation_col;
}
public void setDate_creation_col(String date_creation_col) {
this.date_creation_col = date_creation_col;
}
public String getNom_col() {
return nom_col;
}
public void setNom_col(String nom_col) {
this.nom_col = nom_col;
}
public String getLong_col() {
return long_col;
}
public void setLong_col(String long_col) {
this.long_col = long_col;
}
public String getLat_col() {
return lat_col;
}
public void setLat_col(String lat_col) {
this.lat_col = lat_col;
}
public String getTel_fix_col() {
return tel_fix_col;
}
public void setTel_fix_col(String tel_fix_col) {
this.tel_fix_col = tel_fix_col;
}
public String getTel_mobile_col() {
return tel_mobile_col;
}
public void setTel_mobile_col(String tel_mobile_col) {
this.tel_mobile_col = tel_mobile_col;
}
public String getCreatorcreator() {
return creatorcreator;
}
public void setCreatorcreator(String creatorcreator) {
this.creatorcreator = creatorcreator;
}
public String getHeure_matin_col() {
return heure_matin_col;
}
public void setHeure_matin_col(String heure_matin_col) {
this.heure_matin_col = heure_matin_col;
}
public String getHeure_apresmatin_col() {
return heure_apresmatin_col;
}
public void setHeure_apresmatin_col(String heure_apresmatin_col) {
this.heure_apresmatin_col = heure_apresmatin_col;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
Actually I received all data and console show me : [{"_id":"5e22074673c926147c3a73f5","date_creation_col":"17-01-2020","creator":"Alaeddine","emailcol":"amir#gmail.com","nom_col":"amir","long_col":"10.179326869547367","lat_col":"36.83353893150942","tel_fix_col":"123","tel_mobile_col":"1234","adress_col":"rue Paris mision 34","heure_matin_col":"7","heure_apresmatin_col":"5","type":"collection","imagePath":"mmmmmmmmmmmm"}]
I want to know how to extract for example creator from this Json.
You can use a third-party JSON parser, like Google GSON, as you're already developing for Android. Java does not seem to contain a built-in JSON parser.
See this answer.

Json Parsing and assign to DTO using Jackson

Facing some issue while parsing JSON into DTO.
In Json Getting Response as below
{
"errorMsg": null,
"flag": "S",
"message": "",
"coi_Number": "1234567",
"expiryDate": "7/12/2019 12:00:00 AM"
}
In DTO :
#JsonProperty("errorMsg")
private Object errorMsg;
#JsonProperty("flag")
private String flag;
#JsonProperty("message")
private String message;
#JsonProperty("coi_Number")
private String coiNumber;
#JsonProperty("expiryDate")
private String expiryDate;
#JsonProperty("errorMsg")
public Object getErrorMsg() {
return errorMsg;
}
#JsonProperty("errorMsg")
public void setErrorMsg(Object errorMsg) {
this.errorMsg = errorMsg;
}
#JsonProperty("flag")
public String getFlag() {
return flag;
}
#JsonProperty("flag")
public void setFlag(String flag) {
this.flag = flag;
}
#JsonProperty("message")
public String getMessage() {
return message;
}
#JsonProperty("message")
public void setMessage(String message) {
this.message = message;
}
#JsonProperty("coi_Number")
public String getCoiNumber() {
return coiNumber;
}
#JsonProperty("coi_Number")
public void setCoiNumber(String coiNumber) {
this.coiNumber = coiNumber;
}
#JsonProperty("expiryDate")
public String getExpiryDate() {
return expiryDate;
}
#JsonProperty("expiryDate")
public void setExpiryDate(String expiryDate) {
this.expiryDate = expiryDate;
}
Getting value as null. Please suggest what is the way to resolve it using Spring MVC.
In response getting value but after setting value in DTO getting coiNumber as null.
Try changing private String coiNumber to coi_Number
In response, you are getting key as "coi_Number" but in the entity, you are using this.
Solution 1:
#JsonProperty("coi_Number")
private String coiNumber;
Try changing the above to
#JsonProperty("coi_Number")
private String coi_Number
Solution 2:
If the above solution 1 doesn't work then try changing
#JsonProperty("coi_Number")
to
#JsonProperty("coi_number")

Gson deserialization Expected BEGIN_ARRAY but was STRING [duplicate]

This question already has answers here:
Why does Gson fromJson throw a JsonSyntaxException: Expected BEGIN_OBJECT but was BEGIN_ARRAY?
(2 answers)
Closed 4 years ago.
I get the following json response from my api in my android application, i am using Gson deserialization to parse my data and populate my listview.
API Response:
{
"message":"success",
"success":"1",
"sessionKey":"a422e60213322845b85ae122de53269f",
"data":"[{\"system_id\":1,\"logo_url\":\"https:\\\/\\\/www.beta.system.com\\\/api\\\/icons\\\/3244ffjg.jpg\",\"organization_name\":\"Test Organasation\"}]"
}
My Class:
public class SystemResponse {
#Expose
#SerializedName("message")
private String message;
#Expose
#SerializedName("success")
private String statusCode;
#Expose
#SerializedName("sessionKey")
private String sessionKey;
#Expose
#SerializedName("data")
private List<System> data;
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getSessionKey() {
return sessionKey;
}
public void setSessionKey(String sessionKey) {
this.sessionKey = sessionKey;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<System> getSystems() {
return data;
}
public void setSystems(List<System> data) {
this.data = data;
}
public static class System{
#Expose
#SerializedName("system_id")
private Long systemId;
#Expose
#SerializedName("logo_url")
private String logoUrl;
#Expose
#SerializedName("organization_name")
private String organizationName;
public Long getSystemId() {
return systemId;
}
public void setSystemId(Long systemId) {
this.systemId = systemId;
}
public String getLogoUrl() {
return logoUrl;
}
public void setLogoUrl(String logoUrl) {
this.logoUrl = logoUrl;
}
public String getOrganizationName() {
return organizationName;
}
public void setOrganizationName(String organizationName) {
this.organizationName = organizationName;
}
}
}
Api Request service, omitted the other code:
public Observable<SystemResponse> doServerAccountRequestApiCall(String param) {
return Rx2AndroidNetworking.get(ApiEndPoint.ENDPOINT_GET_ACCOUNTS)
.build()
.getObjectObservable(SystemResponse.class);
}
Request api call in my controller class, omitted the other code.
getCompositeDisposable().add(getDataManager() .doServerAccountRequestApiCall(params))
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(new Consumer<SystemResponse>() {
#Override
public void accept(#NonNull SystemResponse response)
throws Exception {
//error here
}
}, new Consumer<Throwable>() {}));
I am getting getting this error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 92 path $.data
data parameter value is starting with " So it is a String not an array.
Use http://www.jsonschema2pojo.org/ to generate a model class.
Try this model class :
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("message")
#Expose
private String message;
#SerializedName("success")
#Expose
private String success;
#SerializedName("sessionKey")
#Expose
private String sessionKey;
#SerializedName("data")
#Expose
private String data;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getSessionKey() {
return sessionKey;
}
public void setSessionKey(String sessionKey) {
this.sessionKey = sessionKey;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}

Deserializing generic java object returns LinkedTreeMap

I have a generic Java Message object that's represented by the following json string:
{
"type": "Example",
"processTime": 3.4,
"payload":
{
"id": "someString",
"type": "anotherString",
"message": "yetAnotherString"
}
}
The Java Message object is generic. I also have an object called Event. When trying to convert the json into a Message<Event> object using gson, a Message object is returned with the correct json values, but the nested generic object is somehow returned as a "LinkedTreeMap" object instead of an Event object. I know this has something to do with type erasure, but I still can't seem to figure out how to return a Message<Event> from the json.
This is my main():
public class App {
public static void main(String[] args) {
//The json string to convert into a "Message<Event>" object
String jsonString = "{\"type\":\"Example\",\"processTime\":3.4,\"payload\":{\"id\":\"someString\",\"type\":\"anotherString\",\"message\":\"yetAnotherString\"}}";
Message<Event> message = new Message<Event>();
message = message.convertJsonToObject(jsonString, Event.class);
System.out.println(message.getClass().getName()); //returns as a "Message" class -- as expected
System.out.println(message.getPayload().getClass().getName()); //returns as a "LinkedTreeMap" instead of an "Event" object
}
}
Message class:
public class Message<T> {
private String type;
private double processTime;
private T payload;
public Message(String type, double processTime, T payload) {
this.type = type;
this.processTime = processTime;
this.payload = payload;
}
public Message() {
type = null;
processTime = 0;
payload = null;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getProcessTime() {
return processTime;
}
public void setProcessTime(double processTime) {
this.processTime = processTime;
}
public T getPayload() {
return payload;
}
public void setPayload(T payload) {
this.payload = payload;
}
public Message<T> convertJsonToObject(String jsonString, Class<T> classType) {
GsonBuilder gson = new GsonBuilder();
Type collectionType = new TypeToken<Message<T>>() {}.getType();
Message<T> myMessage = gson.create().fromJson(jsonString, collectionType);
return myMessage;
}
#Override
public String toString() {
return new Gson().toJson(this);
}
}
Event class:
public class Event {
private String id;
private String type;
private String message;
public Event(String id, String type, String message) {
this.id = id;
this.type = type;
this.message = message;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
#Override
public String toString() {
return new Gson().toJson(this);
}
}

Categories

Resources