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);
Related
I have one input request DTO for a Patch call
#Data
public class RequestDTO {
String name;
#SerializedName(value= "requestNumber", alternate = {"requestNo"})
String requestNumber;
}
My Controller method looks something like:
#PatchMapping("/path")
public ResponseEntity<ResponseDTO> updateSomething(#RequestBody #Valid RequestDTO requestDTO) {
//some code here
if(requestDTO.getRequestNumber == null) {
log.error("Deserialization failure");
}
//return something
}
When I try to deserialize request DTO using Gson, I am able to do it with both the field names, requestNumber and requestNo
Example:
Gson gson = new Gson();
String input = "{"name": "abc", "requestNumber": "1"};
RequestDTO requestDTO = gson.fromJson(input, RequestDTO.class);
Assert.assertNotNull(requestDTO.getRequestNumber) //Test passed
And
String input = "{"name": "abc", "requestNo": "1"};
RequestDTO requestDTO = gson.fromJson(input, RequestDTO.class);
Assert.assertNotNull(requestDTO.getRequestNumber) //Test passed
Irrespective of field name is requestNumber of requestNo in input JSON, it is deserialized properly.
But whenever I pass a request DTO of the form {"name": "abc", "requestNo": "1"} to my patch call, on deserialization, value of requestNumber field in the deserialized DTO always turns out to be null. Deserialized DTO looks like:
{
"name": "abc",
"requestNumber": null
}
It works well when input field name is requestNumber. What is the reason behind this?
What is best way to deserialize the value in requestBody with both field names?
I cannot stick to only one field name because my actual DTO (this is dummy one) is used by multiple systems and it is not possible to have only either field name.
Spring uses Jackson Object Mapper for deserializing JSON objects. Since #SerializedName annotation belongs to Gson and not to Jackson, it will not take the alternate value. Use #JsonAlias from Jackson for alternate field names.
#JsonAlias("requestNo")
String requestNumber;
This will help in deserializing values declared using both field names.
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.
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" }
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;
}
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;