(De)serialising LocalDate: how to prepare JSON - java

I have a class that represent data in which there is LocalDate field.
public class Student {
private String name;
private LocalDate dob;
//getters and setters
}
In pom.xml I have jackson-modules-java8 so that LocalDate could be deserialized. I'm having difficulty preparing correct JSON to be able to send POST. Here it is:
{ "name" : "John", "dob" : [ 1986::10::06 ] }
In a response to POST I get Cannot deserialize instance ofjava.time.LocalDateout of START_ARRAY token. Decorating the field dob with annotation #JsonFormat(pattern = "yyyy::MM::dd") didnn't work. Three years ago workaround was published but things may have changed since then.

From the w3school description of json values:
In JSON, values must be one of the following data types:
a string
a number
an object (JSON object)
an array
a boolean
null
According this definition your json is not valid because [1986::10::06] is not a valid value.
You need to treat it as a string, adding the " characters around it instead of squared brackets.
The right json must be
{ "name" : "John", "dob" : "1986::10::06" }

The LocalDate API doc says:
A date without a time-zone in the ISO-8601 calendar system, such as
2007-12-03.
So you JSON should be like:
{ "name" : "John", "dob" : "1986-10-06" }

Related

How to extract date from JSON with year, day and month as separate fields in format yyyy-mm-dd

I am new to JSON, to get transaction details of user i am making API call to one of the webservice in the JSON response from the API the transaction date is coming as below
{
"trasanction_date": {
"year": 2021,
"month": 6,
"day": 16
}
}
I need to convert the above date in format yyyy-mm-dd to insert it into Cassandra. Right now how i am converting is, i am creating new JSONObject from above String like
JSONObject trasaction = new JSONObject("{\"trasanction_date\":{\"year\":2021,\"month\":6,\"day\":16}}");
JSONObject date = trasaction.get("trasaction_date");
String year = date.getString("year");
String month = date.getString("month");
String day = date.getString("day");
//concatenating the final result to frame the date
String transactionDate = year+month+Day
Is there a way to efficiently convert the above JSON in format yyyy-mm-dd with out extracting and concatenating the string. Please help with above thanks in advance.
Create TransactionDate.java class witch contains three String fields year, month,day with getters and setters. Then, createTransactionDetails.java class witch have property of type TransactionDate and use gson library to convert JSON string to java object.
You can take a look at this article to see how to use gson
Then inside TransactionDate.java class you can override toString() method to something like this :
#Override
String toString() {
return this.year + " " + this.month + " " + this.day;
}
Finally, instad of returning transactionDate string you can get TransactionDate object from TransactionDetails and return it's String representation.

Dynamic Timezone implementation While json Date Deserialization

Is there way to initialize dynamic timezone while json output for all date formatted values, I have location id input by which I determine the timezone so each output has the location id so can I use this here as below.
#Configuration
public class TimeZoneConfig {
#Value("${ovitag.timezone}")
private String timezone;
#Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() {
return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(TimeZone.getTimeZone("Asia/Kolkata"));
}
}
The above code only change to a particular timezone is it possible here to call the json response here and get that locationId and transform the timezone values dynamically
Json response
{
"VisitDate": "1991-02-19 12:23:56",
"firstName": "dharnisha",
"lastName": "K",
"mainIdentifier": "uhidd90011",
"mobileNumber": "9300921111",
"packageId": "2020"
"locationId":"1234"
}
Timezone is dynamic based on loc id as obtained from below
String timZone = configFileDao.getConfigTimezoneByLocationId(locationId);

How to Parse JSON having data types with values?

I have an issue with JSON data.
In my Json it is having data types with values. not sure how to parse.
ex:
{
"id": "123456",
"name": {
"firstName": {
"String": "Nathon"
},
,
"lastName": {
"String": "Jason"
}
}.
Please help on this
public String map(ObjectNode jsonNode) throws Exception {
return value.get("id");
}
I tried with the above sample code , but i am able to parse only "id"
If you are using Jackson2 then get then name as JsonNode
JsonNode nameNode = value.path("name");
And then again get the firstName and lastName as JsonNode
JsonNode firstName = nameNode.path("firstName");
JsonNode lastName = nameNode.path("lastName");
From JsonNode firstName and JsonNode lirstName get the string value
String name1 = firstName.path("string").asText();
String name2 = lastName.path("string").asText();
Well first of all you don't have to mention the data types in order to parse a JSON appropriately, just create a POJO class matching the structure of JSON then use GSON to parse JSON into a java class
When your json is deserialized into ObjectNode then it is actually represented internally as a map key/value in which value can itself be again a map as is in your case. Visually if you look at it, it would be something like this.
So you would need to follow this structure using get(fieldName) to get the value OR an ObjectNode if it is nested . Remember if the return value is ObjectNode then simply printing it would just return the json fragment it represents, so you would need to call again 'get(fieldName)' on that object.

Handle JSON response date in array

so I'm inserting the date of birth to an API, and the API returns the updated information, which i'm supposed to present on another page after handling the data in java backend.
Here is what gets returned in JSON:
"firstname": "John",
"middlename": "The",
"lastname": "Doe",
"displayName": "John The Doe",
"dateOfBirth": [
1994,
3,
26
]
so what I'm having trouble with, is picking out the 3 (year/month/day) in separate variables, because if theres no 0 in 03 ( mars for example ) i want to add the 0, same goes with day.
Here i'm getting the object:
#Override
public Object getDateOfBirth() {
return get("dateOfBirth");
}
But i'm getting [1994,3,26] which obviously looks very bad displayed on a website.
How would you get the 3 "1994,3,26" in different variables?
Any help is greatly appreciated.
if you are using Java 8 or later, you can use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate.of(year, month, day); //2015-12-22
LocalDate.of(Integer.parseInt(dateOfBirth[0]), Integer.parseInt(dateOfBirth[1]), Integer.parseInt(dateOfBirth[2]));
But i'm getting [1994,3,26] which obviously looks very bad displayed on a website.
How would you get the 3 "1994,3,26" in different variables?
You can transform the output of returned array object into custom format for display purpose. Assuming get("dateOfBirth") returns and Array object. You can do something similar ...
String result = Arrays.toString(dateOfBirthArrayObject).replaceAll("[\\[\\]]", "");
System.out.println(result);
Output: 1994, 3, 26
take a look on this link This can help.
I can recommend you to use the Gson
if you use maven add this dependency to the pom
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
public class MyJsonAsClass
{
private String firstname;
private String middlename;
private String lastname;
private String displayName;
private List<String> dateOfBirth;
public MyJsonAsClass()
{
}
public static MyJsonAsClass fromString(String json)
{
Gson gson = new Gson();
MyJsonAsClass info = gson.fromJson(json, MyJsonAsClass.class);
return info;
}
/*you need to add getters & setters */
public List<String> getdateOfBirth()
{
for (String date : dateOfBirth) {
if (date.length()==1)
date='0'+date;
}
return dateOfBirth;
}

Parsing JSON with java : dynamic keys

I need to create a JSON response with some dynamic fields in java. Here is an example of the JSON response I want to return :
{
"success": true,
"completed_at": 1400515821,
"<uuid>": {
type: "my_type",
...
},
"<uuid>": {
type: "my_type",
...
}
}
The "success" and the "completed_at" fields are easy to format. How can I format the fields? What would be the corresponding java object?
Basically I want to work with 2 java objects :
public class ApiResponseDTO {
private boolean success;
private DateTime completedAt;
...
}
and
public class AuthenticateResponseDTO extends ApiResponseDTO {
public List<ApplianceResponseDTO> uuids = new ArrayList<ApplianceResponseDTO>();
}
These java objects don't correspond to the expected JSON format. It would work if I could change the JSON format to have a list, but I can't change it.
Thanks a lot!
You can massage your data into JSON form using the javax.json library, specifically the JsonObjectBuilder and the JsonArrayBuilder. You'll probably want to nest a few levels of a toJson() method which will either give you the string representation you're looking for, or the JsonObject/JsonArray you desire. Something like this:
JsonArray value = null;
JsonArrayBuilder builder = Json.createArrayBuilder();
for (ApplianceResponseDTO apr : uuids) {
builder.add(apr.toJson());
}
value = builder.build();
return value;

Categories

Resources