Reputation: 248
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.
Upvotes: 1
Views: 1161
Reputation: 3679
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.
Upvotes: 1