While trying to parse the following JSON string:
{
marketplaceId:"MKPL",
asin:"ASIN1",
sourceTimestamp:2013-03-19T23:38:24.054Z,
orderId:"ORD1",
vendorId:"SUPR1",
warehouseId:"SEA8",
inventoryOwnerGroup:376,
lastUpdatedAt:2013-03-19T23:38:23.919Z,
isHighConfidence:true,
quantityArriving:2,
expectedDeliveryDate:2013-03-19T23:38:23.919Z
}
I get the following exception:
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.sql.Timestamp out of VALUE_EMBEDDED_OBJECT token
at [Source: N/A; line: -1, column: -1] (through reference chain: com.amazon.freshwombat.po.PurchaseRecord["lastUpdatedAt"])
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:219)
at org.codehaus.jackson.map.deser.std.StdDeserializer._parseDate(StdDeserializer.java:580)
at org.codehaus.jackson.map.deser.std.TimestampDeserializer.deserialize(TimestampDeserializer.java:28)
at org.codehaus.jackson.map.deser.std.TimestampDeserializer.deserialize(TimestampDeserializer.java:19)
Am I missing something? Thanks!
JSON doesn't support the concept of "dates". It only supports simple data types like strings, numbers, arrays, booleans, etc. So, represent your dates as strings. E.g.:
lastUpdatedAt: "2013-03-19T23:38:23.919Z",
You'll have to do the actual date parsing with other JavaScript facilities/third-party libraries.
If you are using Jackson for JSon to Object conversion you must specify the DateFormat a mapper instance should use in order to generate Date from String values that represents a date or timestamp.
In the case of the of a (mysql) timestamp :
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(format)
Entity entity = mapper.readValue("{ }", Entity.class);
So closely following the advices of #SimpleCoder and with this snippet i guess you shouldn't have problems.
Related
How to dynamic deserialize JSON from method in controller? I use that code:
dynamic dynJson = JsonConvert.DeserializeObject(GetReservedDaysJson().ToString());
And have that error:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: M. Path '', line 0, position 0.'
My JSON from GetReservedDaysJson() function look like that:
["2022-03-29","2022-03-30"]
Unless someone has a better solution. It needs to compare each date with JSON. With the date provided in the model.
you can try this
string json = GetReservedDaysJson();
List<DateTime> dates = JsonConvert.DeserializeObject<List<DateTime>>(json);
{"externalQueryDate":"4018-11-23"}
this is my json string, which is in a column of mysql.
I get it with creditRisk.getCreditRiskDataCodeBased()
and in javascript or in swagger, i see with backslashes:
"{\"externalQueryDate\":\"4018-11-23\"}"
I can use JSON.parse in frontend but , i want to solve this is backend.
even
for
StringWriter sw = new StringWriter();
objectMapper.writer().writeValue(sw, creditRisk.getCreditRiskDataTermBased());
it writes this:
"responseCode": "\"{\\\"externalQueryDate\\\":\\\"4018-11-23\\\"}\""
I tried those
objectMapper.readTree(creditRisk.getCreditRiskDataCodeBased()).toString()
and
objectMapper.writer().writeValue(sw, creditRisk.getCreditRiskDataTermBased());
and
#JsonRawValue
#JsonValue
How can i solve this?
In mysql, it is also without slashes
If you want to parse the json string with jackson objectMapper you need to use 'read' and tell it what class to use to create the parsed object from.
So in your case you could do something like
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\"externalQueryDate\":\"4018-11-23\"}";
Map map = objectMapper.readValue(json, Map.class);
System.out.print(map.get("externalQueryDate"));
I've just used a Map here as I don't know what class you're wanting to parse the json into. If you have a class with an externalQueryDate field you can read into that. You could also use #JsonFormat on the field to tell it what the date format is if you want to parse the value straight into a LocalDate field.
I suggest you write a few simple unit tests to get the hang of escaped quotes in strings. It looks like they're causing you some confusion.
I am using Mule 3.6.1 and in datamapper I have a JSON object which is a string datatype and I need to get the value of a field from the JSON object.
How can I get this value from the JSON object while the object is of type String?
I cannot use the JSON transformer for this.
Thanks for any help
To convert a String of JSON and get one of its field value inside DataMapper, then you can utilize code like this (in DataMapper Script area):
jsonObject = new org.json.JSONObject(input.jsonstring);
output.jsonValue = jsonObject.getString("jsonfield");
In order to convert JSON element to a series of objects. Google GSon library is very helpful.
Example:
import com.google.gson.Gson;
Gson gson = new Gson();
Student studentTest = gson.fromJson(data, Student.class);
System.out.println("Amount: " + studentTest .getStudentName());
I have a JSONArray of JSONObjects that I'm trying to parse with GSON. I'm using FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES. It's parsing correctly for most fields (so the FieldNamingPolicy is set correct), but I'm getting null returned for
{
"image_sq_48x48_url": "url1",
"image_sq_64x64_url": "url2",
"image_sq_96x96_url": "url3"
}
with field names
imageSq48x48Url
imageSq64x64Url
imageSq96x96Url
Maybe a better question would be what is the proper camelCase? I have also tried
imageSq48X48Url
imageSq48X48url
If I map with #SerializedName("image_sq_96x96_url") it parses/populates correctly.
Unfortunately those fieldnames in your JSON don't conform to what Gson looks for using that strategy.
If you create a POJO and serialize it, you can see what the issue is:
class MyPojo
{
String imageSq48x48Url = "hi";
}
The resulting JSON from Gson using that strategy is:
{"image_sq48x48_url":"hi"}
It doesn't consider/look at numeric digits as leading indicators / start of a "word".
If you rename the field to:
String imageSq_48x48Url;
It would work with your JSON example and that strategy.
Basically, you either need to create your own class that implements FieldNamingStrategy that will handle those JSON fieldnames the way you want, or do what you're doing with the #SerializedName annotation.
I use Jackson to deserialize (parse) a simple JSON event, with code like this:
JsonParser parser = ... // Initialized via JsonFactory for simple JSON String
ObjectMapper mapper = new ObjectMapper();
HashMap<String, Object> attributes = mapper.readValue(parser,
new TypeReference<HashMap<String, Object>>() {});
The code works as expected for the several cases I have tested it against, apart from when the JSON input contains the Unicode null value (\u0000).
More specifically, if the JSON String above has a key-value pair that contains Unicode, e.g.
{
... (start K-V pairs),
"UniKey":"\u0000...",
... (end K-V pairs)
}
the parser correctly reads all "start K-V pairs" (which contain no null Unicode) into the attributes HashMap but stops deserialization immediately on encountering the null Unicode value of "UniKey", returning an empty value and never parsing the rest of the JSON String (i.e., the "end K-V pairs").
Is there any way of telling Jackson to ignore null Unicode in deserialization?
Strings containing null (\u0000) are read/printed by some Java methods and not by others, so they are only displayed as truncated. So the value may actually be there, but not displayed by something like System.out.println().