Gson parse an Object from empty string - json

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

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

SpringBoot JSON not deserializing into my request model

I am using SpringBoot and trying to deserialize JSON like:
{
"userId": "Dave",
"queryResults": {
"id": "ABC",
"carData": {.....},
"carId": "Honda",
"status": 0,
"model": "X"
}
}
, into MyRequestModel clas:
public class MyRequestModel {
private String userId;
private String: queryResults;
}
, that is received as #RequestBody parameter in my #PostMapping method that looks like:
#PostMapping
public String postDate(#RequestBody MyRequestModel data) {
...
return "posted";
}
The above queryResults field is supposed to be stored as a CLOB in a database.
Problem I am having is that if I send this JSON to hit my endpoint (PostMapping) method, it cannot deserialize it into MyRequestModel and I get this error:
Cannot deserialize instance of java.lang.String out of START_OBJECT token
at [Source: (PushbackInputStream); line: 3, column: 18] (through reference chain: MyRequestModel["queryResults"])]
I guess the real answer to your question is: if you NEED the queryResults property to be a String, then implement a custom deserializer.
If not, then, use one of the alternatives that Jonatan and Montaser proposed in the other answers.
Implementing a custom deserializer within Spring Boot is fairly straightforward, since Jackson is its default serializer / deserializer and it provides a easy way to write our own deserializer.
First, create a class that implements the StdDeserializer<T>:
MyRequestModelDeserializer.java
public class MyRequestModelDeserializer extends StdDeserializer<MyRequestModel> {
public MyRequestModelDeserializer() {
this(null);
}
public MyRequestModelDeserializer(Class<?> vc) {
super(vc);
}
#Override
public MyRequestModel deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = p.getCodec().readTree(p);
String userId = node.get("userId").asText();
String queryResults = node.get("queryResults").toString();
MyRequestModel model = new MyRequestModel();
model.setQueryResults(queryResults);
model.setUserId(userId);
return model;
}
}
Second, mark your class to be deserialized using your custom deserializer by using the #JsonDeserialize annotation:
MyRequestModel.java
#JsonDeserialize(using = MyRequestModelDeserializer.class)
public class MyRequestModel {
private String userId;
private String queryResults;
}
It's done.
queryResults is a String on Java side but it is an Object on JSON side.
You will be able to deserialize it if you send it in as a String:
{
"userId": "Dave",
"queryResults": "foo"
}
or if you create classes that maps to the fields:
public class MyRequestModel {
private String userId;
private QueryResults queryResults;
}
public class QueryResults {
private String id;
private CarData carData;
private String carId;
private Integer status;
private String model;
}
or if you serialize it into something generic (not recommended):
public class MyRequestModel {
private String userId;
private Object queryResults;
}
public class MyRequestModel {
private String userId;
private Map<String, Object> queryResults;
}
public class MyRequestModel {
private String userId;
private JsonNode queryResults;
}
You have two options to deserialize this request:-
change the type of queryResults to Map<String, Object>, it will accepts everything as an object of key and value. (Not recommended)
public class MyRequestModel {
private String userId;
private Map<String, Object> queryResults;
}
You have to create a class that wraps the results of queryResults as an object.
class QueryResult {
private String id;
private Map<String, Object> carData;
private String carId;
private Integer status;
private String model;
public QueryResult() {}
public QueryResult(String id, Map<String, Object> carData, String carId, Integer status, String model) {
this.id = id;
this.carData = carData;
this.carId = carId;
this.status = status;
this.model = model;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, Object> getCarData() {
return carData;
}
public void setCarData(Map<String, Object> carData) {
this.carData = carData;
}
public String getCarId() {
return carId;
}
public void setCarId(String carId) {
this.carId = carId;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
and make the type of queryResult as shown:-
public class MyRequestModel {
private String userId;
private QueryResult queryResults;
}

How to convert complex Object to Json String

I have following class defined:
public class ClassObjectTwo {
Long a;
Long b;
}
public class ClassObjectThree{
Long c;
Long d;
}
public class ClassObject{
private final ClassObjectTwo obj1;
private final ClassObjectTwo obj2;
private final ClassObjectTwo obj3;
private final Multimap<String, ClassObjectThree> obj4;
}
ClassObject classObj;
Gson gson = new Gson();
String jsonString = gson.toJson(classObj);
return jsonString;
JsonString is not returning anything, How to define Object of object to convert into JSON String ?
How to use InstanceCreator here ?
Not entirely sure, what the issue here is, when you say, it's not returning anything. Try making use of GsonBuilder.
you could use - GsonBuilder, and enable the complexMapKeySerialization as below.
Gson gson = new GsonBuilder().registerTypeAdapter(Instant.class, new InstantConverter()).enableComplexMapKeySerialization()
.setPrettyPrinting().create();
Since the Gson uses, toString() methods, for forming the JSON, make sure to use them.
public class ClassObject{
private final ClassObjectTwo obj1;
private final ClassObjectTwo obj2;
private final ClassObjectTwo obj3;
private final Multimap<String, ClassObjectThree> obj4;
#Override
public String toString() {
return new ToStringBuilder(this)
.append("obj1", obj1)
.append("obj2", obj2)
.append("obj3", obj3)
.append("obj4", obj4)
.toString();
}
}

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

object convert to json how to modify the property key?

i have a json like
"weatherInfo":{
"city":"北京",
"publishDate":"2014年3月4日",
"week":"星期二",
"tempRange":"8℃~-3℃",
"feelTemp":"10",
"time":"16:05",
"temp":"11",
"WD":"北风",
"WS":"2级",
"SD":"27%",
"weather1":"晴"
}
and my class is
public class WeatherVO implements Serializable{
private static final long serialVersionUID = 2348480036959754071L;
#JsonProperty(value="weatherinfo")
private WeatherInfoVO weatherInfoVO;
#JsonIgnoreProperties(ignoreUnknown=true)
public class WeatherInfoVO{
//城市
#JsonProperty(value="city")
private String city;
//发布日期
private String publishDate;
//发布时间
#JsonProperty(value="time")
private String publishTime;
//星期
private String week;
//温度范围
private String tempRange;
//当前时刻温度
#JsonProperty(value="temp")
private String currentTemp;
//风向
#JsonProperty(value="WD")
private String windDirection;
//风力
#JsonProperty(value="WS")
private String windForce;
//当前时刻湿度
#JsonProperty(value="SD")
private String currentHumidity;
//体感温度
private String feelTemp;
//天气描述
private String weatherDesc;
}
}
i want to convert json to object like:
WeatherVO weatherVO = objectMapper.readValue (jsonString, WeatherVO.class);
and i want to return json use org.springframework.http.converter.json.MappingJacksonHttpMessageConverter class
and the return json is
"weatherInfo":{
"city":"北京",
"publishDate":"2014年3月4日",
"week":"星期二",
"tempRange":"8℃~-3℃",
"feelTemp":"10",
"time":"16:05",
"temp":"11",
"WD":"北风",
"WS":"2级",
"SD":"27%",
"weather1":"晴"
}
but i want to return like
"weatherInfo":{
"city":"北京",
"publishDate":"2014年3月4日",
"week":"星期二",
"tempRange":"8℃~-3℃",
"feelTemp":"10",
"publishTime":"16:05",
"currentTemp":"11",
"windDirection":"北风",
"windForce":"2级",
"currentHumidity":"27%",
"weather":"晴"
}
how can i do that?
thanks for your any suggestion and help.
You can achieve this by marking the getter of the field by #JsonIgnore then create another method that get the field and mark it as #JsonProperty.
My advice is to rename first your fields to avoid confusion. I renamed it like the json you have. So for example.
public class WeatherInfoVO{
private String city;
private String publishDate;
private String week;
private String tempRange;
private String feelTemp;
private String time;
private String temp;
private String WD;
private String WS;
private String SD;
private String weather1;
//getters and setters
}
then in you setters method mark the appropriate #JsonProperty.
#JsonProperty(value="time")
public void setTime(String time) {
this.temp = temp;
}
#JsonProperty(value="temp")
public void setTemp(String temp) {
this.temp = temp;
}
#JsonProperty(value="WD")
public void setWD(String WD) {
this.WD = WD;
}
#JsonProperty(value="WS")
public void setWS(String WS) {
this.WS = WS;
}
#JsonProperty(value="SD")
public void setSD(String SD) {
this.SD = SD;
}
#JsonProperty(value="weather1")
public void setWeather1(String weather1) {
this.weather1 = weather1;
}
//other setters here
and in your getters, make sure to add #JsonIgnore to the fields you want to rename. Since you declare it as #JsonIgnore, you need to create another getter and mark it as #JsonProperty. Do it only to the fields you are going to rename, in your case the fields are time, temp, WD, WS, SD and weather1 only. Here's an example.
#JsonIgnore
public void getTime(){
return time;
}
#JsonProperty(value="publishTime")
public void getPublishTime(){
return time;
}
#JsonIgnore
public void getTemp(){
return temp;
}
#JsonProperty(value="currentTemp")
public void getCurrentTemp(){
return temp;
}
#JsonIgnore
public void getWD(){
return WD;
}
#JsonProperty(value="windDirection")
public void getWindDirection(){
return WD;
}
#JsonIgnore
public void getWS(){
return WS;
}
#JsonProperty(value="windForce")
public void getWindForce(){
return WS;
}
#JsonIgnore
public void getSD(){
return SD;
}
#JsonProperty(value="currentHumidity")
public void getCurrentHumidity(){
return SD;
}
#JsonIgnore
public void getWeather1(){
return weather1;
}
#JsonProperty(value="weather")
public void getWeather(){
return weather1;
}