Getting a JSONException because of a colon - java

I'm getting my JSON values from a linkedHashMap
LinkedHashMap<String,Object> lst = JsonPath.parse(json).read("$.projects[0].issuetypes[0].fields");
This is the JSON I'm trying to parse :
{
"required": false,
"schema": {
"type": "string",
"custom": "com.atlassian.jira.plugin.system.customfieldtypes:textfield",
"customId": 10161
},
"name": "Error Code",
"operations": [
"set"
]
}
Then I was thinking that this would do the job
JSONObject jsonObject = new JSONObject(lst.get(key).toString());
But then I got this exception:
Exception in thread "main" org.codehaus.jettison.json.JSONException: Expected a ',' or '}' at character 95 of {required=false, schema={type=string, custom=com.atlassian.jira.plugin.system.customfieldtypes:textfield, customId=10161}, name=Error Code, operations=["set"]}
Character 95 is the colon between customfieldtypes and textfield
What could be wrong with this ?

You are trying to parse a serialized object, which is not valid JSON.
lst.get(key).toString()
does not produce JSON.

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

How to get string values in to json and fetch message value from below request [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
{
"Header": {
"AppId": "appiddfdsf324",
"RecId": "fdsfrecid79878_879898_8797",
"SecureRefId": "fsdf5679567fsd_6789678",
"Type": "Other",
"Ver": "9.0.0",
"StartTS": "2016-09-26:07:48.798798-04:00"
},
"Application": {
"APP_OS": "Windows",
"APP_Runtime": ".Net67986",
"APP_AppName": "MPS",
"APP_AppVersion": "9.0.0.0",
"Host": "fsdhajkfh657895fsdajf",
"Channel": "N/A",
"APP_ReqId": "2f3d7987987-78987-987987-897-da"
},
"Service": {
"Key": "modification process",
"CallType": "HGDL",
"Operation": "processrequest",
"Port": "n/a"
},
"Results": {
"Elapsed": 0,
"Message": "Message Succesfully Deleted",
"TraceLevel": "Information"
},
"Security": {
"Vendor": "abfsdf"
},
"Extended_Fields": {
"CustomerId": "4564987987",
"MessageId": "768789fsdafasdf987987987fasdf",
"TimeElapsed": "1272.8171"
}
}
in above string value we are capturing from website result values we will get in a string format by using selenium webdriver.
This i need to convert and read value of "Message"
Note : i have tried below code
JsonElement jelement = new JsonParser().parse((String) elementText);
JsonObject jobject = jelement.getAsJsonObject();
jobject.getAsJsonObject("Results");
This above will provide complete result value of Result json but i required to fetch values which is present with "Message"
Below first line creates the JSONObject by passing String [which is of JSON format and it should be in JSON format, otherwise it will through an exception]
In Second line , as you have a JSON Object now, you can fetch any element from that,
e.g to fetch the value for Message, which is an element of "Results" object which is of JSON type,
we can access any element by using . and depending on what are you fetching use get
e.g getString -> for getting String,
getInt->for getting Integer,
JSONObject-> for getting an JSONObject
getJSONArray-> for getting a JSONArray
JSONObject jsonObj=new JSONObject(pass your String) //This converts in to JSON Object
jsonObj.getJSONOObject("Results").getString("Message"); //As result internally itself is a JSON Object

Stringifying a Java Object throwing Error in JSON.parse Javascript

I have defined a class Email having following details:
Email:
String name;
String subject;
List<String> attachment;
String jsonContent;
....
In above class, jsonContent variable is loaded with a strinigified json object.
Once an Email object is created, I am stringifying the whole Email object and sending to client.
I need to parse Email object in client and render it in UI.
But it throws parsing error for Email object in client, i.e.
JSON.parse(emailString);
because jsonContent field is having double quotes within it.
It is a problem of stringifying a JAVA object having a jsonContent variable which is already stringified.
One way to fix it is define jsonContent variable as a object rather than as a String.
Is there any other fix for it?
Example Email JSON:
{
"id": "e4682ec0-a7c3-4f4d-abcd-f404f5fdb1eb",
"entityType": "email",
"subject": "Presentation 1",
"from": "aaa <a#a.com>",
"to": [
"undisclosed-recipients:;"
],
"cc": [],
"bcc": [
"jack.porter#forwardaccelerator.com"
],
"recievedDate": 1423101398000,
"recievedDateString": "Wed, 4 Feb 2015 12:26:38 -0800",
"bodyText": " Please find the link to my recent presentation",
"jsonContent": "{
"typeOfMail": "NormalMail",
"normalMail": {
"mailType": "NormalMail",
"paragraphs": [
"Pleasefindthelinktomyrecentpresentation"
]
}
}"
}
You will need to escape a lot of strings to get stuff as strings.
to store a json object in a json object you need to escape it.
so
"jsonContent": "{
"typeOfMail": "NormalMail",
"normalMail": {
"mailType": "NormalMail",
"paragraphs": [
"Pleasefindthelinktomyrecentpresentation"
]
}
}"
becomes
"jsonContent": "{\"typeOfMail\": \"NormalMail\",\"normalMail\":{\"mailType\":\"NormalMail\",\"paragraphs\":[\"Pleasefindthelinktomyrecentpresentation\"]}}"
Now if you want to compile it in java, this is how it should look like if you would type it manually as an Java string(execute snippet)
var json = {
"id": "e4682ec0-a7c3-4f4d-abcd-f404f5fdb1eb",
"entityType": "email",
"subject": "Presentation 1",
"from": "aaa <a#a.com>",
"to": [
"undisclosed-recipients:;"
],
"cc": [],
"bcc": [
"jack.porter#forwardaccelerator.com"
],
"recievedDate": 1423101398000,
"recievedDateString": "Wed, 4 Feb 2015 12:26:38 -0800",
"bodyText": " Please find the link to my recent presentation",
"jsonContent": "{\"typeOfMail\": \"NormalMail\",\"normalMail\":{\"mailType\":\"NormalMail\",\"paragraphs\":[\"Pleasefindthelinktomyrecentpresentation\"]}}"
}
console.log("This is the json object having a string with json");
console.log(json);
console.log("This is it parsed as string");
var x = {hello:JSON.stringify(json)};
console.log(JSON.stringify(x).substring(10,JSON.stringify(x).length-2));
document.getElementById('content').textContent = JSON.stringify(x).substring(10,JSON.stringify(x).length-2);
<div id="content"></div>
And this is how it would look like in a JSON file/request answer thats sent
{
"id": "e4682ec0-a7c3-4f4d-abcd-f404f5fdb1eb",
"entityType": "email",
"subject": "Presentation 1",
"from": "aaa <a#a.com>",
"to": [
"undisclosed-recipients:;"
],
"cc": [],
"bcc": [
"jack.porter#forwardaccelerator.com"
],
"recievedDate": 1423101398000,
"recievedDateString": "Wed, 4 Feb 2015 12:26:38 -0800",
"bodyText": " Please find the link to my recent presentation",
"jsonContent": "{\"typeOfMail\": \"NormalMail\",\"normalMail\":{\"mailType\":\"NormalMail\",\"paragraphs\":[\"Pleasefindthelinktomyrecentpresentation\"]}}"
}
Now I don't see why you want jsonContent as a string, as you could just pass it as an object(remove the quotes surrounding it so you get
"jsonContent": {
"typeOfMail": "NormalMail",
"normalMail": {
"mailType": "NormalMail",
"paragraphs": [
"Pleasefindthelinktomyrecentpresentation"
]
}
}
and if you need it as string in javascript you can just do JSON.stringify(json.jsonContent); to get the same result easier.

Json string to json object conversion

I have looking to similar questions but i was not able to solve my problem .I have tried parsing my json response both into a Json array and Json object but every time , i am getting this exception of string to json object.
I guess may be the problem is with my Json response.
results = { "type": 1, "user_log": "ahsan.tahir.92_/var/www/html/2014-10-11__15-54-52__50sec.txt_res", "freq": 0.01, "coordina": [ [-37], [-9], [-20], [-12], [-22], [-9], [-22], [-15], [-25], [-7], [-20], [-12], [-20], [-9], [-25], [8], [-23], [-11], [-18], [-13], [-19], [-10], [-21], [-12], [-25], [-11], [-17], [-12], [-22], [-13], [-21], [3] ], "tot_time": 40.11, "tot_distace": 100, "stroke_each_pool": [ [16], [16] ], "tot_stroke": [ [16], [16] ], "split": [ [20.22], [19.89] ], "timing_turn": 7.04, "cycle_Rate_l": [ [2.22], [2.2680001] ], "cycle_Rate_r": [ [2.224], [2.27] ], "mean_velocity": [ [2.4727993], [2.5138261] ], "stroke_length": [ [3.125], [3.125] ], "stroke_freq": [ [79.077431], [77.419357] ], "roll_peaks": [ [-44.10043335], [55.79428101], [-61.51541138], [54.7466507], [-62.09820557], [55.01488495], [-62.48770142], [53.44023132], [-70.32449341], [51.8399353], [-65.84837341], [53.5617981], [-63.50210571], [55.9821167], [-62.37905121], [39.42669678], [-43.44207764], [63.20912933], [-59.19660187], [50.6708374], [-63.8214798], [54.57595062], [-63.31864166], [53.82037354], [-66.93650818], [52.36277008], [-65.23461151], [52.89829254], [-62.78508759], [51.17367554], [-62.87123108], [59.13114929] ], "mean_roll_dx": [ [52.475822], [54.73027] ], "mean_roll_sx": [ [61.531971], [60.950779] ], "std_roll_dx": [ [5.4471908], [4.3127728] ], "std_roll_sx": [ [7.6123171], [7.4134283] ], "mean_roll": [ [57.003899], [57.840527] ], "std_roll": [ [7.9220791], [6.6817732] ], "mean_pitch": [ [-5.5227709], [-5.2282872] ], "std_pitch": [ [-5.5227709], [-5.2282872] ], "clean_stroke_time": [ [15.92], [16.84] ], "errore": 227, "fatal_error": { "_ArrayType_": "double", "_ArraySize_": [0,0], "_ArrayData_": null } }
and i am parsing it like this :
JSONObject reader = new JSONObject(in);
JSONObject sys = reader.getJSONObject("results");
Any idea what am i missing here ?
My exception is as follows :
org.json.JSONException: Value type of type java.lang.String cannot be converted to JSONObject
There is no results field in the results string you have posted, is that the issue. In any case, please go ahead and reformat your question to more accurately reflect what you are doing, and include the error message you are seeing.
Actually, are you referring to the error message in the JSON output? That seems to be a JSON-encoded error message that was output by whatever service you called. There seems to be some issue with the data you are passing to that service.
This:
results = {rest of response here}
is not valid JSON.
Perhaps you meant to return this:
{"results": {rest of response here}}
... or just
{rest of response here}
I may have Misunderstood your question, but where are you parsing the Json response using something like
JSONObject jsonObject = (JSONObject) jsonParser.parse(strippedJSON);
where strippedJSON the response received from API.
Your reader object is your results object itself.
JSONObject resultsJSON = new JSONObject(in);
System.out.println("User Log: " + resultsJSON.get("user_log"));
You're getting the exception because there's no results object in your input JSON string i.e. you're receiving your results object without a JSON wrapper around it.
If you are using javascript
try this
var parsed_data = JSON && JSON.parse(results) || $.parseJSON(results);

Jackson Error Unexpected character ('}' (code 125))

Hey i got an issue based on deserialization with jackson, here what i've tried and the error i got.
ERROR : com.fasterxml.jackson.core.JsonParseException: Unexpected character ('}' (code 125)): was expecting double-quote to start field name
Java Code
List<Contact> ds = mapper.readValue(data, mapper.getTypeFactory().constructCollectionType(List.class, Contact.class));
//OR this one
List<Contact> ds = mapper.readValue(data, new TypeReference<List<Contact>>() {});
My JSON
[
{
"id": "200",
"name": "Alexia Milano",
"email": "minalo#gmail.com",
"prenom": "xx-xx-xxxx,x - street, x - country",
}, {
"id": "201",
"name": "Johnny Depp",
"email": "johnny_depp#gmail.com",
"prenom": "xx-xx-xxxx,x - street, x - country",
}
]
If you use json validator, you can see more detailed error message:
Parse error on line 6:
...ntry", }, { "id
---------------------^
Expecting 'STRING'
you have extra comma there after "xx-xx-xxxx,x - street, x - country". If you remove it from both two places, you have valid JSON and Jackson parsing works.
It's because your last entries, there is an , after your last value. Thats why jackson expects another field.

Categories