Handle JSON response date in array - java

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

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.

how to parse a JSON from file?

I have a basic question, but I can't make this work for an android app.
I have a JSON file that looks like this:
{
"catches":[
{
"time":"Jan 14, 2021 10:40:04 PM",
"amount":1,
"condition":0.8
},
{
"time":"Jan 15, 2021 12:05:14 PM",
"amount":"2",
"condition":1.0
},
{
"time":"Jan 16, 2021 11:30:04 PM",
"amount":"3",
"condition":null
}
]
}
How could I parse the JSON from a file stored in internal storage and assign the values to variables?
In C# I could do something like this:
static void Main(string[] args)
{
string fPath = "C:/Temp/myJSON.json";
using (StreamReader r = new StreamReader(fPath))
{
string json = r.ReadToEnd();
Root el;
el = JsonConvert.DeserializeObject<Root>(json);
//variable which later would be used in for a TextView
var lastRecord = el.catches[el.catches.Count - 1].time;
}
}
But I don't know how to make something like this in java. Thanks.
You can fetch the file content as string:
fun getDataAsStringFromPath(path: String): String {
val file = File(this.javaClass.classLoader?.getResource(path)?.path)
return file.readText(Charset.defaultCharset())
}
Make sure you save this file in resources directory at the same place where res lies.
I would recommend you look at a JSON parsing library. The one I recommend is Jackson. It is quite easy to parse the String to your object.
First,y ou create a Data class. In your example, you will need two: CacheItem and Container (rename appropriately if you feel like it)
class CacheItem {
private String time;
private Integer amount;
private Double condition;
// Getters and Setters
}
class Container {
private List<CacheItem> caches;
// Getter and Setter
}
Now, where you want to parse the String from the file, get the Object Mapper (see Jackson API for this) and simply call Container container = mapper.readValue(string, Container.class);

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 use ObjectMapper to read in an Json format to an Object which contains String and List<String>

I have an Object like this:
public class Marketplace {
private String name;
private int id;
private List<String> supportedLanguages;
}
and I have an input Json format String like this:
{
"name":"US",
"id":1,
"supportedLanguages":{"en_US", "es_US"}
}
I tried something like this first but failed:
objectMapper.readValue(marketplaceInJsonString, Marketplace.class);
Then I tried something like this but still failed:
JsonNode jsonNode = objectMapper.readValue(marketplaceInJsonString, JsonNode.class);
Marketplace marketplace = new Marketplace(jsonNode.get("name").asText()), jsonNode.get("id").asInt(), jsonNode.findValuesAsText("supportedLanguages"));
I think the key problem here is that I don't find the correct way to map supportedLanguages as a List of String.
And is there any format problem of the Json String input?
Please help, and really appreciate.
Your json string is not valid json
change it to
{
"name": "US",
"id": 1,
"supportedLanguages": [
"en_US",
"es_US"
]
}
Testing code:
String marketplaceInJsonString = "{\"name\":\"US\",\"id\":1,\"supportedLanguages\":[\"en_US\",\"es_US\"]}";
ObjectMapper objectMapper = new ObjectMapper();
Marketplace marketplace = objectMapper.readValue(marketplaceInJsonString, Marketplace.class);
System.out.println(marketplace);
//output
Marketplace(name=US, id=1, supportedLanguages=[en_US, es_US])

(De)serialising LocalDate: how to prepare JSON

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

Categories

Resources