convert json String to array java object by Gson - json

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

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

JSON array within an object is not being parsed

I'm using hibernate, spring, and fasterxml/Jackson to create JSON based rest services.
I'm sending in the following JSON:
{
"allParts" : true,
"aogLocation" : "LAS",
"companyId" : "20",
"controlNo" : "1",
"controlSeq" : "1234",
"dateNeeded" : "2020-02-24",
"timeNeeded" : "800",
"employeeId" : "bob",
"inventoryLocation" : "LAS",
"requestType" : "STOCK",
"shippingAddress": "123 e. st. Las Vegas, NV 12345",
"tailNo" : "abc",
"partsRequestLines" : [
{
"location": "LAS",
"lineNote" : "I need this part really bad",
"requestedPartDescription" : "it makes a plane go.",
"requestedPartNumber" : "abc-123",
"requestedQuantity" : 10
}
]
}
To be parsed into the following classes:
#Getter
#Setter
public class PartsRequestDto extends AbstractDto {
private Boolean allParts;
private String aogLocation;
private Date chgdate;
private Integer chgpage;
private String chgprog;
private String chgtype;
private String chguser;
private String companyId;
private String controlNo;
private Integer controlSeq;
private Date dateNeeded;
private String employeeId;
private String inventoryLocation;
private Date requestDate;
private Integer requestId;
private String requestType;
private String shippingAddress;
private Integer status;
private Timestamp sysEnd;
private Timestamp sysStart;
private String tailNo;
private String timeNeeded;
private Timestamp transStart;
private List<PartsRequestLineDto> partsRequestLines;
public PartsRequestDto() {
}
public PartsRequestDto(Boolean allParts, String aogLocation, Date chgdate, Integer chgpage, String chgprog,
String chgtype, String chguser, String companyId, String controlNo, Integer controlSeq,
Date dateNeeded, String employeeId, String inventoryLocation, Date requestDate, Integer requestId,
String requestType, String shippingAddress, Integer status, Timestamp sysEnd, Timestamp sysStart,
String tailNo, String timeNeeded, Timestamp transStart) {
this.allParts = allParts;
this.aogLocation = aogLocation;
this.chgdate = chgdate;
this.chgpage = chgpage;
this.chgprog = chgprog;
this.chgtype = chgtype;
this.chguser = chguser;
this.companyId = companyId;
this.controlNo = controlNo;
this.controlSeq = controlSeq;
this.dateNeeded = dateNeeded;
this.employeeId = employeeId;
this.inventoryLocation = inventoryLocation;
this.requestDate = requestDate;
this.requestId = requestId;
this.requestType = requestType;
this.shippingAddress = shippingAddress;
this.status = status;
this.sysEnd = sysEnd;
this.sysStart = sysStart;
this.tailNo = tailNo;
this.timeNeeded = timeNeeded;
this.transStart = transStart;
}
}
#Getter
#Setter
#AllArgsConstructor
public class PartsRequestLineDto implements Serializable {
private Integer id;
private Integer reqId;
private String location;
private String requestType;
private Date etaTimestamp;
private Date neededTimestamp;
private Date requestedTimestamp;
private Integer status;
private String tailNumber;
private String lineNote;
private String packingListId;
private String requestedPartDescription;
private String requestedPartNumber;
private Integer requestedQuantity;
public PartsRequestLineDto() {
}
}
I send that JSON into the following REST API:
#RequestMapping(value = "/create", method = RequestMethod.POST)
public PartsRequestDto createPartsRequest(PartsRequestDto partsRequestDto) throws Exception {
PartsRequest partsRequest = partsRequestService.constructPartsRequestFromDto(partsRequestDto);
PartsRequestDto response = partsRequestService.createPartsRequest(partsRequest);
return response;
}
It parses the PartsRequest object just fine, but sets the partsRequestLines list to null. Can someone tell me how to get Jackson/REST to parse the sub-object list correctly?
I figured it out. My method signature on the API was missing a #RequestBody annotation.

How to create json annotated POJO class

I see some class like this in the code I am looking, and wonder how
it was generated, they looks like generated by a plugin or by eclipse itself, I know eclipse can create a POJO file for your through wizard, but how do I get results like below?
public class Item implements Serializable{
private static final long serialVersionUID = 3868244754652312286L;
#JsonProperty("name")
private String name;
#JsonProperty("quantity")
private String quantity;
#JsonProperty("price")
private String price;
#JsonProperty("tax")
private String tax;
#JsonProperty("sku")
private String sku;
#JsonProperty("originalPrice")
private String originalPrice;
#JsonIgnore
private HashMap<String, Object> additionalProperties = new HashMap<>();
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}

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

Modifying objects list fileds saved as LONGBLOB in MySQL

I have a table "Project" in my MySQL Databse that contains an ArrayList saved as LONGBLOB (FiledDetailsData).
public class ProjectEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String projectName;
private String city;
private int nbFields;
private List<FiledDetailsData> FiledDetails;...
I already have alot of data saved and would like to keep it. The problem is that I had to change to structure of FiledDetailsData to add new fields
I've changed it from
#Embeddable
#XmlRootEllement
public class FiledDetailsData implements Serializable`{
private String id;
private String lot;
private String number;
private String street;
private String size;
private String status;
to
#Embeddable
#XmlRootEllement
public class FiledDetailsData implements Serializable`{
private String id;
private String lot;
private String number;
private String street;
private String size;
private String status;
private BigDecimal extraField;
private BigDecimal extraParking;
When I try to run the application with the previous data, I get this error
Could not deserialize object from byte array. Internal Exception: local class incompatible
I can fin it by deleting the LONGBLOB in my DAtaBase and recreating it, but then I lose all my data.
here are my save/edit methods
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
Thank you.