Best way to convert String to json in Android(Java)? - java

I am doing a statistics application using a 3rd party API. what I got from the API; json from webview with userAgent. I need to take this as a string and then convert it to json, but when I set it to the string value, I get the error "constant string too long". I found some solution but I don't think it's the best method.What is the best way to keep a big String in a variable?
Thanks for any help.
my convert code below here
Gson g = new Gson();
User user = g.fromJson(sampleJson, User.class);
Log.d("comingData",user.getGlobal_blacklist_sample());
My json has much more than user(500+) showed inside Users array (100000+ characters)
Added sample Json string below here
{
"sections": null,
"global_blacklist_sample": null,
"users": [{
"pk": 1111111111,
"username": "sample_username",
"full_name": "Sample Name :)",
"is_private": false,
"profile_pic_url": "https://sammple_pic",
"profile_pic_id": "2315322835352130707_36052201610",
"is_verified": false,
"has_anonymous_profile_picture": false,
"latest_reel_media": 0
}, {
"pk": 22222,
"username": "sample_username2",
"full_name": "Sample Name2 :)",
"is_private": false,
"profile_pic_url": "https://sammple_pic2",
"profile_pic_id": "22222222222",
"is_verified": false,
"has_anonymous_profile_picture": false,
"latest_reel_media": 0
}]
}

Related

Get json object in Array based on key and value in Java

I have a Json body like the example below. I need to extract the value from a key that has another key with a specific value in an array. I am passing in a JsonNode with everything in the detail component of the message, I can easily extract from each level, however, I'm struggling with the array.
In this case, I need to extract the value of "value" (Police/Fire/Accident Report) from the object in the array which has a key/value pair of "name":"documentTitle". I understand this is a JSONArray, but I can't find a good example that shows me how to extract the values for an object in the array that contains a certain key/value pair, I don't think I can rely on getting the object in position [2] in the array as the same objects may not always be present in the additionalMetadata array.
Sample Json:
"sourceVersion": "1.0",
"eventId": "8d74b892-810a-47c3-882b-6e641fd509eb",
"clientRequestId": "b84f3a7b-03cc-4848-a1e8-3519106c6fcb",
"detail": {
"stack": "corona",
"visibilityIndicator": null,
"documentUid": "b84f3a7b-03cc-4848-a1e8-3519106c6fcb",
"additionalMetadata": [
{
"name": "lastModifiedDate",
"value": "2021-05-21T04:53:53Z"
},
{
"name": "documentName",
"value": "Police/Fire Report, 23850413, 2021-05-20 14:51:23"
},
{
"name": "documentTitle",
"value": "Police/Fire/Accident Report"
},
{
"name": "documentAuthor",
"value": "System Generated"
},
{
"name": "lastModifiedBy",
"value": "System Updated"
},
{
"name": "createdBy",
"value": "System Generated"
},
{
"name": "documentDescription",
"value": "Police/Fire Report received"
},
{
"name": "organizationCode",
"value": "Claims"
}
]
}
}```
Loop through the json array and extract the json object with name documentTitile. From that json object you can get the value
Well, either the JSON framework you're using supports this out of the box (check the documentation) or you could convert it manually to a map:
List<AdditionalMetadataEntry> additionalMetadata;
[...]
Map<String, String> additionalMetadataMap = additionalMetadata.stream().collect(Collectors.toMap(AdditionalMetadataEntry::getName, AdditionalMetadataEntry::getValue));
I was able to figure it out. I created a new node off the existing notificationBody JsonNode, then parsed through the metadata key/value pairs:
String docTitle = "";
JsonNode additionalMetadata = notificationBody.get("detail").get("additionalMetadata");
for (JsonNode node: additionalMetadata) {
String name = node.get("name").asText();
String value = node.get("value").asText();
if(name.equals("documentTitle")){
docTitle = value;
}
}

Control characters in Json causing JsonParsingException

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

Separate each name-value pair in a JSON string to separate lines in a java string

I have a Java Spring MVC Web Application. I am trying to implement a form submission where the user will be submitting the form and an email would be sent to the user with the form data. I will receive the form data as JSON string. But the email sent with this data doesn't look readable. I have tried the following code to make the data more readable, but doesn't seem to make much difference:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonData);
String message = gson.toJson(je);
My JSON String looks something like below:
[ { "name": "FirstName", "value": "Abcd" }, { "name": "LastName", "value": "Efgh" }, { "name": "Email", "value": "test.mail#test.com" }, { "name": "PhoneNumber", "value": "9876543210" }, { "name": "Selected Locations", "value": " loc1, loc2, loc3" }, { "name": "Message", "value": "Hi" }, { "name": "g-recaptcha-response", "value": "03AMPJSYULxjYiDRiNxcOSVYxXR9F8dX5pqIYAZ6_F2igAwGvanS4Vh1Lm47ByS2qGELQ9W1h" } ]
I am looking for an option at least to bring name-value pair into separate lines so that it is in some readable manner when received through an email. Is there any way to do this. The form can be generic, SO I may not be able to map this string to any Java object.
I have already tried the following link and the solution does not work for me:
Pretty-Print JSON in Java
I also don't see many helpful details online regarding this. I am trying to put each name-value pair in a new line of the generated string to send the data as email.

Jackson converting dynamic json to map

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.

Java - How to get object value in JSON array?

i have a JSON like example below and i'm trying to get some values, for example value of.
results.shipper.id
{
"results": [
{
"updated": false,
"notification": false,
"some_data": {
"id": 15989,
"pieces": 0,
},
"shipper": {
"updated": false,
"notification": false,
"id": 1587,
"parent": {
"updated": false
},
I'm trying to get value by this way:
String test = shipmentData.getJSONObject("shipper").getString("id");
But it always throws a exception. I think, that exception is caused because of the i am not accessing to the values via "results" array.
How can i easy access to the value what i need.
I tried find some helpers (Gson, fast-json, etc..) but it seems to be a quite complicated for using (i would like to work with JSON tree for direct access to values "on-the-fly" or access to values like to a object, it means.. Object.InnerObject.value ).
So question is how can i do it right?
Thanks for any advice.
JSON needs to be traversed in order to access id:
JSONArray results = shipmentData.getJSONArray("results");
JSONObject first = results.getJSONObject(0);
JSONObject shipper = first.getJSONObject("shipper");
Integer id = shipper.getInt("id");
Parse int to string:
String id = String.valueOf(shipper.getInt("id"));

Categories