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.
Related
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
This is the error I continue to get while attempting to parse my incoming JSON response data. I'm utilizing the OkHttp library to create and call, and the API I'm getting results from returns everything in an Array as follows:
[
{
"id": 4256,
"image_url": "https://cdn.pandascore.co/images/league/image/4256/OMEN_Challenger_Series_2019.png",
"live_supported": false,
"modified_at": "2019-10-30T10:02:42Z",
"name": "OMEN Challenger",
"series": [
{
"begin_at": "2019-11-01T03:30:00Z",
"description": null,
"end_at": null,
"full_name": "2019",
"id": 1932,
"league_id": 4256,
"modified_at": "2019-10-30T09:11:40Z",
"name": null,
"prizepool": "50000 United States Dollar",
"season": null,
"slug": "cs-go-omen-challenger-2019",
"winner_id": null,
"winner_type": null,
"year": 2019
}
],
"slug": "cs-go-omen-challenger",
"url": "https://omengaming.co/omen_cs/",
"videogame": {
"current_version": null,
"id": 3,
"name": "CS:GO",
"slug": "cs-go"
}
},
{...},
{...},
{...},
{...},
]
I found a lot of folks recommending Gson to parse it into a custom class, but the following code, in theory, should work and it isn't. The parsing doesn't even begin due to it expecting BEGIN_OBJECT and it being BEGIN_ARRAY:
String jsonData = response.body().string();
Gson gson = new Gson();
EventInfo test = gson.fromJson(jsonData, EventInfo.class);
class EventInfo {
String imageURL;
String name;
JSONArray series;
}
You are trying to parse it into an object. But in your response, you can clearly see that it's a list. The parent POJO should have been a list. And inside that list, you should have created another POJO.
In your response parent is found as array but you need to add first parent as JSON object and child as a array or object.
You need response like this
{
"YourArrayName":[
"YourChildObjName":{
"id": 4256,
"image_url": "https://cdn.pandascore.co/images/league/image/4256/OMEN_Challenger_Series_2019.png",
"live_supported": false,
"modified_at": "2019-10-30T10:02:42Z",
"name": "OMEN Challenger",
"series": [
{
"begin_at": "2019-11-01T03:30:00Z",
"description": null,
"end_at": null,
"full_name": "2019",
"id": 1932,
"league_id": 4256,
"modified_at": "2019-10-30T09:11:40Z",
"name": null,
"prizepool": "50000 United States Dollar",
"season": null,
"slug": "cs-go-omen-challenger-2019",
"winner_id": null,
"winner_type": null,
"year": 2019
}
],
"slug": "cs-go-omen-challenger",
"url": "https://omengaming.co/omen_cs/",
"videogame": {
"current_version": null,
"id": 3,
"name": "CS:GO",
"slug": "cs-go"
}
},
{...},
{...},
{...},
{...},
]
}
I hope this can help You!
Thank You
So, I figured it out. Originally I was receiving the same error at a later point; namely when it got to the series key value in the first JSONObject. The original error occurred because I was trying to parse series as a JSONArray, rather than a List<JSONObject> The corrections are below:
String jsonData = response.body().string();
Gson gson = new Gson();
Type listType = new TypeToken<List<EventInfo>>() {}.getType();
List<EventInfo> test = gson.fromJson(jsonData, listType);
And the EventInfo class:
class EventInfo {
String imageURL;
String name;
List<JSONObject> series;
}
Thank you for the advice everyone!
I have this java method:
public class ReadIssues {
// Reads from a Json object
protected JsonArray readJson() throws IOException {
JsonArray issueArray = null;
ClassLoader cl = Thread.currentThread().getContextClassLoader();
// Get input stream for reading the specified resource
InputStream inputStream = cl.getResourceAsStream("GitHubIssue.json");
// Create JsonReader to read JSON data from a stream
Reader reader = new InputStreamReader(inputStream, "UTF-8");
JsonReader jsonReader = Json.createReader(reader);
try{
// Create an object model in memory
issueArray = jsonReader.readArray();
System.out.println("ReadIssues issueArray: " + issueArray);
}
finally {
if (inputStream != null) {
inputStream.close();
}
if (jsonReader != null) {
jsonReader.close();
}
}
return issueArray;
}
It throws this exception:
Exception in thread "main" javax.json.stream.JsonParsingException: Unexpected char 117 at (line no=1, column no=5, offset=4)
at org.glassfish.json.JsonTokenizer.unexpectedChar(JsonTokenizer.java:601)
at org.glassfish.json.JsonTokenizer.nextToken(JsonTokenizer.java:418)
at org.glassfish.json.JsonParserImpl$ObjectContext.getNextEvent(JsonParserImpl.java:453)
at org.glassfish.json.JsonParserImpl.next(JsonParserImpl.java:363)
at org.glassfish.json.JsonParserImpl.getObject(JsonParserImpl.java:333)
at org.glassfish.json.JsonParserImpl.getValue(JsonParserImpl.java:182)
at org.glassfish.json.JsonParserImpl.getArray(JsonParserImpl.java:326)
at org.glassfish.json.JsonParserImpl.getArray(JsonParserImpl.java:164)
at org.glassfish.json.JsonReaderImpl.readArray(JsonReaderImpl.java:129)
at paulcarron.issuetracker.ReadIssues.readJson(ReadIssues.java:42)
at paulcarron.issuetracker.App.main(App.java:22)
The problem seems to be issueArray = jsonReader.readArray();. I think that body value in my JSON contains characters such as \n and \r.
I came across one post that suggested doing something like json = json.replaceAll("\r?\n", ""); but that was where json was a String. What should I do in my case where I'm using a JsonReader object?
JSON Sample
[ { url: 'https://api.github.com/repos/TestOrg/test2/issues/4',
repository_url: 'https://api.github.com/repos/TestOrg/test2',
labels_url: 'https://api.github.com/repos/TestOrg/test2/issues/4/labels{/name}',
comments_url: 'https://api.github.com/repos/TestOrg/test2/issues/4/comments',
events_url: 'https://api.github.com/repos/TestOrg/test2/issues/4/events',
html_url: 'https://github.com/TestOrg/test2/issues/4',
id: 347593311,
node_id: 'MDU6SXNzdWUzNDc1OTMzMTE=',
number: 4,
title: 'test issue 2',
user:
{ login: 'my-repo',
id: 32067576,
node_id: 'MDQ6VXNlcjMyMDY3NTc2',
avatar_url: 'https://avatars1.githubusercontent.com/u/32067576?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/my-repo',
html_url: 'https://github.com/my-repo',
followers_url: 'https://api.github.com/users/my-repo/followers',
following_url: 'https://api.github.com/users/my-repo/following{/other_user}',
gists_url: 'https://api.github.com/users/my-repo/gists{/gist_id}',
starred_url: 'https://api.github.com/users/my-repo/starred{/owner}{/repo}',
subscriptions_url: 'https://api.github.com/users/my-repo/subscriptions',
organizations_url: 'https://api.github.com/users/my-repo/orgs',
repos_url: 'https://api.github.com/users/my-repo/repos',
events_url: 'https://api.github.com/users/my-repo/events{/privacy}',
received_events_url: 'https://api.github.com/users/my-repo/received_events',
type: 'User',
site_admin: false },
labels: [],
state: 'open',
locked: false,
assignee: null,
assignees: [],
milestone: null,
comments: 0,
created_at: '2018-08-04T06:34:50Z',
updated_at: '2018-08-04T06:34:50Z',
closed_at: null,
author_association: 'CONTRIBUTOR',
body: 'In order to help resolve your issue as quickly as possible please provice the following information when \r\n\r\n1. What is the issue?\r\nAnother one!\r\n\r\n2. What are the steps to recreate the issue?\r\n\r\n\r\n3. Do you have any relevant code samples? If so, please provice them.\r\n\r\n\r\n4. Have you made any specific configurations?\r\n\r\n\r\n5. Do you get an error? If so please include it and any stack trace.\r\n\r\n\r\n6. What version of the API are you using?\r\n',
performed_via_github_app: null,
score: 1 },
{ url: 'https://api.github.com/repos/TestOrg/test2/issues/2',
repository_url: 'https://api.github.com/repos/TestOrg/test2',
labels_url: 'https://api.github.com/repos/TestOrg/test2/issues/2/labels{/name}',
comments_url: 'https://api.github.com/repos/TestOrg/test2/issues/2/comments',
events_url: 'https://api.github.com/repos/TestOrg/test2/issues/2/events',
html_url: 'https://github.com/TestOrg/test2/issues/2',
id: 324450775,
node_id: 'MDU6SXNzdWUzMjQ0NTA3NzU=',
number: 2,
title: 'Something really bad',
user:
{ login: 'my-repo',
id: 32067576,
node_id: 'MDQ6VXNlcjMyMDY3NTc2',
avatar_url: 'https://avatars1.githubusercontent.com/u/32067576?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/my-repo',
html_url: 'https://github.com/my-repo',
followers_url: 'https://api.github.com/users/my-repo/followers',
following_url: 'https://api.github.com/users/my-repo/following{/other_user}',
gists_url: 'https://api.github.com/users/my-repo/gists{/gist_id}',
starred_url: 'https://api.github.com/users/my-repo/starred{/owner}{/repo}',
subscriptions_url: 'https://api.github.com/users/my-repo/subscriptions',
organizations_url: 'https://api.github.com/users/my-repo/orgs',
repos_url: 'https://api.github.com/users/my-repo/repos',
events_url: 'https://api.github.com/users/my-repo/events{/privacy}',
received_events_url: 'https://api.github.com/users/my-repo/received_events',
type: 'User',
site_admin: false },
labels: [],
state: 'open',
locked: false,
assignee: null,
assignees: [],
milestone: null,
comments: 1,
created_at: '2018-05-18T15:15:21Z',
updated_at: '2018-06-22T12:45:17Z',
closed_at: null,
author_association: 'CONTRIBUTOR',
body: 'In order to help resolve your issue as quickly as possible please provice the following information when \r\n\r\n1. What is the issue?\r\nIts all going wrong!!\r\n\r\n2. What are the steps to recreate the issue?\r\nStep 1\r\nStep 2\r\nStep n\r\n\r\n\r\n3. Do you have any relevant code samples? If so, please provice them.\r\nbla\r\n\r\n4. Have you made any specific configurations?\r\nN/A\r\n\r\n5. Do you get an error? If so please include it and any stack trace.\r\nError: Invalid input\r\n\r\n6. What version of the API are you using?\r\n1.2.0\r\n',
performed_via_github_app: null,
score: 1 } ]
Your input is not valid JSON. The first line is the best example.
[ { url: 'https://api.github.com/repos/TestOrg/test2/issues/4',
All object key names in JSON need to be in quotes. Hence, first line corrected:
[ { "url": 'https://api.github.com/repos/TestOrg/test2/issues/4',
Ditto for all the other key names in your objects. Your input is actually valid JavaScript. So to correct your string, I just pasted your original text into a javascript console (node or the browser F12 console will work) and did this:
x = <paste of your string above>
JSON.stringify(x)
Then I ran the output (sans leading and trailing quotes) through https://jsonformatter.org/ to pretty print to give you back the corrected text below.
As a matter of fact, just using the online pretty printer was how I found the parse error to begin with.
[
{
"url": "https://api.github.com/repos/TestOrg/test2/issues/4",
"repository_url": "https://api.github.com/repos/TestOrg/test2",
"labels_url": "https://api.github.com/repos/TestOrg/test2/issues/4/labels{/name}",
"comments_url": "https://api.github.com/repos/TestOrg/test2/issues/4/comments",
"events_url": "https://api.github.com/repos/TestOrg/test2/issues/4/events",
"html_url": "https://github.com/TestOrg/test2/issues/4",
"id": 347593311,
"node_id": "MDU6SXNzdWUzNDc1OTMzMTE=",
"number": 4,
"title": "test issue 2",
"user": {
"login": "my-repo",
"id": 32067576,
"node_id": "MDQ6VXNlcjMyMDY3NTc2",
"avatar_url": "https://avatars1.githubusercontent.com/u/32067576?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/my-repo",
"html_url": "https://github.com/my-repo",
"followers_url": "https://api.github.com/users/my-repo/followers",
"following_url": "https://api.github.com/users/my-repo/following{/other_user}",
"gists_url": "https://api.github.com/users/my-repo/gists{/gist_id}",
"starred_url": "https://api.github.com/users/my-repo/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/my-repo/subscriptions",
"organizations_url": "https://api.github.com/users/my-repo/orgs",
"repos_url": "https://api.github.com/users/my-repo/repos",
"events_url": "https://api.github.com/users/my-repo/events{/privacy}",
"received_events_url": "https://api.github.com/users/my-repo/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "open",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 0,
"created_at": "2018-08-04T06:34:50Z",
"updated_at": "2018-08-04T06:34:50Z",
"closed_at": null,
"author_association": "CONTRIBUTOR",
"body": "In order to help resolve your issue as quickly as possible please provice the following information when \r\n\r\n1. What is the issue?\r\nAnother one!\r\n\r\n2. What are the steps to recreate the issue?\r\n\r\n\r\n3. Do you have any relevant code samples? If so, please provice them.\r\n\r\n\r\n4. Have you made any specific configurations?\r\n\r\n\r\n5. Do you get an error? If so please include it and any stack trace.\r\n\r\n\r\n6. What version of the API are you using?\r\n",
"performed_via_github_app": null,
"score": 1
},
{
"url": "https://api.github.com/repos/TestOrg/test2/issues/2",
"repository_url": "https://api.github.com/repos/TestOrg/test2",
"labels_url": "https://api.github.com/repos/TestOrg/test2/issues/2/labels{/name}",
"comments_url": "https://api.github.com/repos/TestOrg/test2/issues/2/comments",
"events_url": "https://api.github.com/repos/TestOrg/test2/issues/2/events",
"html_url": "https://github.com/TestOrg/test2/issues/2",
"id": 324450775,
"node_id": "MDU6SXNzdWUzMjQ0NTA3NzU=",
"number": 2,
"title": "Something really bad",
"user": {
"login": "my-repo",
"id": 32067576,
"node_id": "MDQ6VXNlcjMyMDY3NTc2",
"avatar_url": "https://avatars1.githubusercontent.com/u/32067576?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/my-repo",
"html_url": "https://github.com/my-repo",
"followers_url": "https://api.github.com/users/my-repo/followers",
"following_url": "https://api.github.com/users/my-repo/following{/other_user}",
"gists_url": "https://api.github.com/users/my-repo/gists{/gist_id}",
"starred_url": "https://api.github.com/users/my-repo/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/my-repo/subscriptions",
"organizations_url": "https://api.github.com/users/my-repo/orgs",
"repos_url": "https://api.github.com/users/my-repo/repos",
"events_url": "https://api.github.com/users/my-repo/events{/privacy}",
"received_events_url": "https://api.github.com/users/my-repo/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "open",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 1,
"created_at": "2018-05-18T15:15:21Z",
"updated_at": "2018-06-22T12:45:17Z",
"closed_at": null,
"author_association": "CONTRIBUTOR",
"body": "In order to help resolve your issue as quickly as possible please provice the following information when \r\n\r\n1. What is the issue?\r\nIts all going wrong!!\r\n\r\n2. What are the steps to recreate the issue?\r\nStep 1\r\nStep 2\r\nStep n\r\n\r\n\r\n3. Do you have any relevant code samples? If so, please provice them.\r\nbla\r\n\r\n4. Have you made any specific configurations?\r\nN/A\r\n\r\n5. Do you get an error? If so please include it and any stack trace.\r\nError: Invalid input\r\n\r\n6. What version of the API are you using?\r\n1.2.0\r\n",
"performed_via_github_app": null,
"score": 1
}
]
This is the JSON response I am getting from the server :
{
"0": {
"pk": 41,
"fields": {
"heading": "Empty Lecture Slot",
"notification": "There is a free lecture available right now for TE B on 2018-05-02 8:00-9:00",
"date": "2018-04-25",
"priority": 1,
"has_read": false,
"action": "/dashboard/set_substitute/91959"
},
"model": "Dashboard.specificnotification"
}
}
Here is the Java code used for parsing this JSON object :
JSONObject jsonObject = new JSONObject(response);
This is the error I am getting in the catch block :
org.json.JSONException: No value for {"0": {"pk": 41, "fields": {"heading": "Empty Lecture Slot", "notification": "There is a free lecture available right now for TE B on 2018-05-02 8:00-9:00", "date": "2018-04-25", "priority": 1, "has_read": false, "action": "/dashboard/set_substitute/91959"}, "model": "Dashboard.specificnotification"}}
How do I parse this object in Android.
Im not sure, but doesn't JSON arrays start like this?:
[
{
}
]
Also the "0" seems to be not required. It will be automatically ordered
EDIT: you can also check online if your json is valid. Just google Json formatter.
I've got a method below, which is parsing JSON. However I've run into an error (which you can see from the title), where it is saying "org.json.JSON.typeMismatch" .
Trying to log the names that are getting output however having no luck. I've little experience with cracking JSON (as you can probably tell from this), so wondering how to go about fixing this issue.
private Boolean parse()
{
try
{
JSONArray ja=new JSONArray(jsonData);
JSONObject jo;
realms.clear();
for (int i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
String name = jo.getString("name");
Log.d("",name);
//realms.add(name);
}
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
And the JSON I am trying to parse into here is:
{
"realms": [{
"type": "pvp",
"population": "low",
"queue": false,
"status": true,
"name": "Aegwynn",
"slug": "aegwynn",
"battlegroup": "Misery",
"locale": "de_DE",
"timezone": "Europe/Paris",
"connected_realms": ["aegwynn"]
}, {
"type": "pve",
"population": "low",
"queue": false,
"status": true,
"name": "Aerie Peak",
"slug": "aerie-peak",
"battlegroup": "Reckoning / Abrechnung",
"locale": "en_GB",
"timezone": "Europe/Paris",
"connected_realms": ["bronzebeard", "aerie-peak"]
}]
(there is more to this but I'd rather not copy it all)
Not sure if perhaps I'm not addressing the "realms" array? Just would appreciate any help on this! As I can't see quite why I'm getting a mismatch?
Kind Regards
J G
Your JSON string show up here it is a JSONObject not a JSONArray, so that you must init an JSONObject with this string, after that get a JSONArray with name realms from previous JSONObject. Here is an example for your reference
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.