Java - Cannot deserialize a json without double quotes using ObjectMapper - java

I have a response coming from API in the following format
{"schema":[output_item, score],
"data":[[item1, 1], [item2, 2]]}
I am trying to serialize and deserialize this json using
Class1 obj = getFromApiCall();
ObjectMapper o = new ObjectMapper();
map.put("first", o.writeAsString(obj)); // Map can only accept strings
String res = map.get("first");
Object obj2 = o.readValue(res, Class1)
This is the error I am getting:
Unexpected character ('o' (code 111)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
at [Source: java.io.StringReader#68bba850; line: 1, column: 13]
How do I make sure that I can serialize and deserialize the objet coming from API call?

Related

How to ignore invalid value and set null value when use jackson paring json string from webfront?

Is there a good way to change the parsing strategy,even comes out a value cant convert to specific type just set null and continue parsing.
Here is the error info.
15:39:29 WARN (DefaultHandlerExceptionResolver.java:424) Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.math.BigDecimal` from String "-": not a valid representation; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.math.BigDecimal` from String "-": not a valid representation
at [Source: (PushbackInputStream); line: 1, column: 1483] (through reference chain: com.vicson.SGHDGD.base.model.DailyOutputUpdatePojo["sheet0"]->com.vicson.SGHDGD.base.model.UpdateSheet["insertRows"]->java.util.ArrayList[1]->com.vicson.SGHDGD.base.model.DailyOutput["weekOutputDRatio"])
The most simple way is to have String field that will be successfully deserialized from JSON. And then parse BigDecimal in setter/constructor that receives field value. Like this:
public void setWeekOutputDRatio(String value){
try{
this.weekOutputDRatio = new BigDecimal(value.toCharArray())
} catch (Exception ignored) {
this.weekOutputDRatio = DEFAULT_VALUE;
}
}

How to send List value in Request Body to Rest Api

Hi i have written a Rest Service to accept List of Long values as input via RequestBody and the code for the same is given below:
#DeleteMapping("/files")
public ResponseEntity<?> deletefiles(#RequestBody List<Long> ids) {
fileService.deleteSelectedfiles(ids);
return ResponseEntity.ok().build();
}
When i try to hit the above url from Postman i am getting the below error:
"JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: [![enter image description here][1]][1]Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token\n at [Source: (PushbackInputStream); line: 1, column: 1]"
In Postman i am sending data as Raw data in the following format
{"ids": [1 ,2]}
Can anyone help me on this
Your payload is expected to be a
[1 ,2]
Instead of
{"ids": [1 ,2]}
The first option is a json array and the second example is a json body.
You can use the first one with your #RequestBody List<Long> ids or the second one with #RequestBody YourData data where
class YourData {
List<Long> ids
}
#RequestMapping(YOUR_REQUEST_MAPPINGS)
public void testArrayOfValues(#RequestParam List<String> values)
{
}

unable to parse json using objectMapper of jackson where json value contains \\

I am de serializing json string to plain java object using jackson's ObjectMapper class. ObjectMapper is throwing an exception
json string I am trying to deserialize is
String input="{\"id\":\"30329\",\"appId\":\"3301\",\"nodeId\":1556537156187,\"data\":\"select id,obt_marks,'\\\\m' as dummy from ltc_test_1\"}";
value for data key contains \ which is causing the problem, is their a way to escape this. i want this value as is in my POJO
It can work by replacing each occurrence of \ with \\ so string will look like
\"data\":\"select id,obt_marks,'\\\\m' as dummy from ltc_test_1\"
Question: How this can be achieved using java,is there any setting in objectMapper or Jackson to tackle this problem ?
Below is pojo which i will get after de-serialization
public class WorkflowProcessInfo {
private Long id;
private Long appId;
private Long nodeId;
private String data;
}
////Code I am using for deserialization
ObjectMapper mapper = new ObjectMapper();
mapper.configure(Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, false);
mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true); mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
true);
mapper.setSerializationInclusion(Include.NON_NULL);
try{
return mapper.readValue(inputJson, WorkflowProcessInfo.class);
}catch(Exception e){
syso(e.getMessage())}
I expecting WorkflowProcessInfo object with values as present in json meaning, data attribute of pojo should look like below
WorkflowProcessInfo.data="select id,obt_marks,'\\m' as dummy from ltc_test_1"
instead i am getting below exception
com.fasterxml.jackson.core.JsonParseException: Unrecognized character
escape 'm' (code 109) at [Source: java.io.StringReader#1ea9f6af;
line: 1, column: 84]

Java jersey client consumes JsonArray of jsonArray

I have a special kind of parsing JSON url :
[{"exchangeRates":[{"currencyISO":"AUD","currencyShortName":"dolar"}]}]
to do that i need to pass by a proxy and a jersey client :
URLConnectionClientHandler ch = new URLConnectionClientHandler(new ConnectionFactory());
Client client = new Client(ch);
WebResource resource = client.resource("https://api.xxxx");
resource.type(MediaType.APPLICATION_JSON);
ExchangeRates[] responseMsg = resource.path("/openapi/xxxx").get(ExchangeRates[].class);
the response is :
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.xxx.ExchangeRates out of START_ARRAY token at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream#236cfcf; line: 1, column: 1]
ExchangeRates is a list of ExchangeRate object.
I can't find a way how to parse this json.Any recommandation ?

jsonMappingException org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at

I am getting below exception while parsing-
JsonMappingException org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at [Source: [B#3f5fb6a4; line: 1, column: 1]
I found several questions with same exception issue but couldn't solve my problem.
You are trying to parse a JSON object as a list. Try changing
List<Social> topics = objectMapper.readValue(response.data, objectMapper.getTypeFactory().constructCollectionType(List.class, Social.class));
into something like:
Social topics = objectMapper.readValue(response.data, Social.class);
Use this
JSONObject jsonObject = new JSONObject(response.data);
JSONArray jsonArray = jsonObject.getJSONArray("newUsers");
List<UserObject > userObject = new ObjectMapper().readValue(jsonArray.toString() , new TypeReference<List<UserObject>>(){});
for JSONObject use java-json.jar

Categories