I have a complex json structure that is returned from the server. The issue here is that I need to parse this json and deserialize it and store it in a new mapping structure - not like the json file. Can someone tell me how can I do this using gson? Thanks
Here is a part of my json:
{
"direct_from_operator": 3,
"yearly_id": {
"$oid": "559f9934783a8731def494dc"
},
"calculation_amount": 121.2,
"handset": {
"monthly_price": 0,
"name": "Sony Xperia Z3 Copper (4G)",
"handset": 475,
"retailer": 3,
"model_img": "",
"payment_level_id": 1,
"plan": 488,
"model": 152,
"upfront_price": 149,
"model_name": "Sony Xperia Z3"
},
"internals": [
{
"description": "",
"meta_name": "national voice unlimited",
"main_category": 0,
"is_primary": true,
"data_format": "Unlimited",
"ui_display": 0,
"loc_types": [
0,
0
],
"name": "Vodafone Unlimited Min Voice",
"id": 147,
"data_level_mb": null,
"is_external": false
},
{
"description": "",
"meta_name": "national voice calls only trailer",
"main_category": null,
"is_primary": false,
"data_format": "",
"ui_display": 0,
"loc_types": [
0,
0
],
"name": "Vodafone Special Numbers",
"id": 217,
"data_level_mb": null,
"is_external": false
}
]
}
Note: I want to store all of this in one model class.
If your model class has the same attributes than the Json that you want to deserialize, try:
Gson gson = new GsonBuilder().create();
YourModelClass yourModelClass = gson.fromJson(yourJsonAttribute, YourModelClass.class);
1- You can create GSON models online by using following link:
http://www.jsonschema2pojo.org/
2-After this use following tutorial:- http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
Related
I must do a concept test to get a json structure and convert in object in java like this Map<String,Double> with Jackson. But the data has these format:
```
"reversedSellId": "reversed trxId from PayU", "merchant":"idMerchant",
"detail": {
LOAN_CAPITAL: 1234,123,
LOAN_INTEREST: 1234,123,
LOAN_ADMON_FEE: 1234,123,
LOAN_IVA_ADMON_FEE: 1234,123,
LOAN_OVERDUE_INTEREST: 0,
LOAN_COLLECTION_MANAGEMENT: 0,
LOAN_IVA_COLLECTION_MANAGEMENT: 0
},
"currency": "COP"
}```
But When put this Json in a Json reader formatted is no allow because its structured is incorrect. So I need know really how would be the structure correct.
Thanks. Is in Java 8.
Valid JSON format:
{
"reversedSellId": "reversed trxId from PayU",
"merchant": "idMerchant",
"detail": {
"LOAN_CAPITAL": 1234.123,
"LOAN_INTEREST": 1234.123,
"LOAN_ADMON_FEE": 1234.123,
"LOAN_IVA_ADMON_FEE": 1234.123,
"LOAN_OVERDUE_INTEREST": 0,
"LOAN_COLLECTION_MANAGEMENT": 0,
"LOAN_IVA_COLLECTION_MANAGEMENT": 0
},
"currency": "COP"
}
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('c-480b-9f29-27b4de54c85b')/drive/items('01QZDPV46NIERRXLPDDRHIYT4HGDYL2CZS')/workbook/worksheets('Sheet123')/tables('1')/rows",
"value": [
{
"#odata.id": "/users('9af3784f-924c-480b-9f29-27b4de54c85b')/drive/items('01QZDPV46NIERRXLPDDRHIYT4HGDYL2CZS')/workbook/worksheets(%27%7B77104C57-F2DA-49CE-B55C-9D7D458A%7D%27)/tables(%271%27)/rows/itemAt(index=0)",
"index": 0,
"values": [
[
100,
"fname1",
"lname1",
123,
"fname1#gmail"
]
]
},
{
"#odata.id": "/users('9a24c-480b-9f29-27b4de54c85b')/drive/items('01QZDPVYT4HGDYL2CZS')/workbook/worksheets(%27%7B77104C57-F2DA-49CED458A%7D%27)/tables(%271%27)/rows/itemAt(index=1)",
"index": 1,
"values": [
[
102,
"fname2",
"lname2",
345,
"fname2#gmail.com"
]
]
}
]
}
I am accessing the rows of an excel from sharepoint using
Microsoft graph api and doing so i am getting the above response.
I am trying to remove the unnecessary part from the above json like
"#odata.id" field its value, field "index":its value and extract the
field "values": [] from json string and store in HashMap of type Employee
using mulesoft or java.
I am trying to extract the "values": [ [ 102, "fname2", "lname2", 345, "fname2#gmail.com" ]: inside the json response.
The JSON-java library is easy to use.
import org.json.*;
JSONObject obj = new JSONObject(jsonStr);
Object values = obj.getJSONArray("value").getJSONObject(0).getJSONArray("values");
I have a String as below stored in datasets_detail column of table item_action_info :
[{
"datasetAttributeId": 5,
"nextUpdate": 1587546084,
"lastSuccessfulRefreshTime": 1587546084,
"refreshActionId": 2,
"errorCode": 0,
"isMFAInstanceRefreshRequired": false
}, {
"datasetAttributeId": 6,
"nextUpdate": 1587546084,
"lastSuccessfulRefreshTime": 1587546084,
"refreshActionId": 2,
"errorCode": 0,
"isMFAInstanceRefreshRequired": false
}, {
"datasetAttributeId": 8,
"nextUpdate": 1587546084,
"lastSuccessfulRefreshTime": 1587546084,
"refreshActionId": 2,
"errorCode": 0,
"isMFAInstanceRefreshRequired": false
}]
I want replace value for each occurrences of "lastSuccessfulRefreshTime".
How to i do in Java?
Below is sample piece of code. Please advice in completing the same.
String strJson =CommonUtils.clobStringConversion(resultSet.getClob("DATASETS_DETAILS"));
// complete the rest code here
If you want to manipulate it as a JSON object, then you can do it via Google GSON.
String strJson =CommonUtils.clobStringConversion(resultSet.getClob("DATASETS_DETAILS"));
Gson gson = new Gson();
List<StringMap> parsedObject = new Gson().fromJson(strJson, List.class);
// Final String
String newReplacedString = gson.toJson(parsedObject.stream().map((item) -> {
// Put your new value here
item.put("lastSuccessfulRefreshTime", "Replaced Value");
return item;
}).collect(Collectors.toList()));
I have a problem where some structure of the json is fixed while some part is dynamic. The end output has to be an object of type
Map<String,List<Map<String,String>>>
I am pasting a sample json code for which the jackson work -
{
"contentlets": [
{
"template": "8f8fab8e-0955-49e1-a2ed-ff45e3296aa8",
"modDate": "2017-01-06 13:13:20.0",
"cachettl": "0",
"title": "New Early Warnings",
"subscribeToListIi": "am#zz.com",
"inode": "15bd497-1d8e-4bc7-b0f4-c799ed89fdc9",
"privacySetting": "public",
"__DOTNAME__": "New gTLD Early Warnings",
"activityStatus": "Completed",
"host": "10b6f94a-7671-4e08-9f4b-27bca80702e7",
"languageId": 1,
"createNotification": false,
"folder": "951ff45c-e844-40d4-904f-92b0d2cd0c3c",
"sortOrder": 0,
"modUser": "dotcms.org.2897"
}
]
}
ObjectMapper mapper = new ObjectMapper();
Map<String,List<Map<String,String>>> myMap=mapper.readValue(responseStr.getBytes(), new TypeReference<HashMap<String,List<Map<String,String>>>>() {});
The above code is working fine but when the json changes to (basically a metadata tag is added) it is not able to convert to map.
{
"contentlets": [
{
"template": "8f8fab8e-0955-49e1-a2ed-ff45e3296aa8",
"modDate": "2017-01-06 13:13:20.0",
"cachettl": "0",
"title": "New gTLD Early Warnings",
"subscribeToListIi": "aml#bb.com",
"inode": "15bd4057-1d8e-4bc7-b0f4-c799ed89fdc9",
"metadata": {
"author": "jack",
"location": "LA"
},
"privacySetting": "public",
"__DOTNAME__": "New gTLD Early Warnings",
"activityStatus": "Completed",
"host": "10b6f94a-7671-4e08-9f4b-27bca80702e7",
"languageId": 1,
"createNotification": false,
"folder": "951ff45c-e844-40d4-904f-92b0d2cd0c3c",
"sortOrder": 0,
"modUser": "dotcms.org.2897"
}
]
}
This is expected since the type of the value of metadata is not a String. If you change the type of the map accordingly then it works:
Map<String,List<Map<String,Object>>> myMap = mapper.readValue(reader, new TypeReference<HashMap<String,List<Map<String,Object>>>>() {});
Of course you are left with the problem that values in the map are not of the same type. so you need to ask yourself what is the desired data structure you want and how you further process it. However, one cannot deserialize a json structure into a simple String.
I have a small test application I'm writing in Java to parse some JSON from the Reddit API. Some sample JSON I'm looking to parse would be like this:
[
{
"kind": "Listing",
"data": {
"modhash": "1jq62oyvwe15aaba7eb18b0b4363b567a00750766351e03dcc",
"children": [
{
"kind": "t3",
"data": {
"domain": "businessinsider.com",
"media_embed": {},
"levenshtein": null,
"subreddit": "Android",
"selftext_html": null,
"selftext": "",
"likes": null,
"saved": false,
"id": "n17u2",
"clicked": false,
"title": "CONFESSION OF A NON-APPLE-FANBOY: Even If The Samsung Galaxy Nexus Is Better, I'm Still Buying An iPhone",
"media": null,
"score": 0,
"over_18": false,
"hidden": false,
"thumbnail": "http://e.thumbs.redditmedia.com/sL0dCwGAvWqnY_sd.jpg",
"subreddit_id": "t5_2qlqh",
"author_flair_css_class": null,
"downs": 2,
"is_self": false,
"permalink": "/r/Android/comments/n17u2/confession_of_a_nonapplefanboy_even_if_the/",
"name": "t3_n17u2",
"created": 1323127132,
"url": "http://www.businessinsider.com/apple-iphone-versus-samsung-galaxy-nexus-2011-12",
"author_flair_text": null,
"author": "FormulaT",
"created_utc": 1323101932,
"num_comments": 0,
"ups": 1
}
}
],
"after": null,
"before": null
}
},
{
"kind": "Listing",
"data": {
"modhash": "1jq62oyvwe15aaba7eb18b0b4363b567a00750766351e03dcc",
"children": [],
"after": null,
"before": null
}
}
]
What I'm trying to accomplish is to get just a few values out of this JSON, e.g. the title and the author. I'm using Jackson to handle the JSON, and the code I'm using looks like this:
URLConnection conn = redditURL.openConnection();
BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
ObjectMapper mapper = new ObjectMapper();
RedditComment comment = mapper.readValue(buf, RedditComment.class);
Iterator itr = comment.getData().getChildren().listIterator();
I created the RedditComment and other needed classes using the JSONGen website (http://jsongen.byingtondesign.com/). However, when parsing the JSON from the BufferedReader, Jackson throws this exception:
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of com.test.RedditAPI.RedditComment out of START_ARRAY token
at [Source: java.io.BufferedReader#3ebfbbe3; line: 1, column: 1]
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.StdDeserializationContext.mappingException(StdDeserializationContext.java:212)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromArray(BeanDeserializer.java:869)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:597)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2723)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1877)
at com.test.RedditAPI.main.returnRedditComment(Main.java:17)
Does anyone have any ideas? I've been scratching my head for a few hours now.
EDIT: Thanks to #Chin Boon and #Chris, I came up with the following (after switching to GSON):
Gson gson = new Gson();
List<RedditComment> comment = gson.fromJson(buf, new TypeToken<List<RedditComment>>() {}.getType());
List<RedditChildren> children = comment.get(1).getData().getChildren();
System.out.println(children.get(1).getData().getAuthor());
but that throws the following exception:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.test.RedditAPI.RedditChildren
Apologies if I'm being a bother, I've looked around the API and there isn't any reference of LinkedHashMaps, so I don't know why it's popping up here.
The problem is that the response is an array of entries. Try:
List<RedditComment> comment = mapper.readValue(buf,new TypeReference<List<RedditComment>>(){});
if you have not already invested too much time into Jackson, may i recommend you looking at GSON, here is a tutorial that should have you started.
Google GSON API maps your JSON string into a domain object.
http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/
Also, you can use a JSON parser to see your JSON.