Json string to json object conversion - java

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

Related

Translation of empty array element in XML to JSON became null in Oracle Service Bus Pipeline

I'm facing an issue when working with Oracle Service Bus. I want to translate XML to JSON as the response but when using nxsd in OSB pipeline to do that translation the empty array (<in:<ARRAYNAME>/>) in XML will be translated as "<ARRAYNAME>":[ null ]. The expected result is "<ARRAYNAME>":[], without null.
Here is the current response:
{
"data": [ null ],
"description": "Success",
"transactionId": null,
"status": 0
}
Here is the expected response:
{
"data": [ ] ,
"description": "Success",
"transactionId": null ,
"status": 0
}

Extract a particular json field [ ] from json string and store in HashMap using Mulesoft or Java

{
"#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");

Getting a JSONException because of a colon

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.

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.

read json file and parse inner json array in java

{
"vers": 0.01,
"config": {
"rate": "perhr",
"valueColumns": [
"vCPU",
"ECU",
"memoryGiB",
"storageGB",
"linux"
],
"currencies": [
"USD"
],
"regions": [
{
"region": "us-east",
"instanceTypes": [
{
"type": "generalCurrentGen",
"sizes": [
{
"size": "t2.micro",
"vCPU": "1",
"ECU": "variable",
"memoryGiB": "1",
"storageGB": "ebsonly",
"valueColumns": [
{
"name": "linux",
"prices": {
"USD": "0.013"
}
}
]
},
{
"size": "t2.small",
"vCPU": "1",
"ECU": "variable",
"memoryGiB": "2",
"storageGB": "ebsonly",
"valueColumns": [
{
"name": "linux",
"prices": {
"USD": "0.026"
}
}
]
}
]
}
]
}
]
}
}
Hi, i wanted to read this json file. I tried various ways from google but getting a null at valuesColumns. I have to read sizes array and have to put in list.
I think it will help your cause if you format your json. As it is it's quite hard to read. Googling for a JSON beautifier quickly found me this one.
When working with JSON your browser console provides a nice environment for inspecting and playing with the data. I pasted it into the browser console and did (hit enter after each line):
var x = { ... paste JSON here ... }
x
x.config
x.config.valueColumns
This tells me that x is a JSON object, config is a JSON object and valueColumns is a JSON array
Now to java. Grab yourself a json library, and accessing valueColumns will be something like:
JSONObject x = new JSONObject("{ ... JSON string ... }");
JSONObject config = x.getJSONObject("config");
JSONArray valueColumns = config.getJSONArray("valueColumns");
You can then iterate over valueColumns and pull out what you need.
Note that the above only gets you to the first valueColumns array under config. By following the same principle you can go deeper into the structure and get out the valueColumns for the objects in the sizes array if that's what you're really after.
For parsing json to java there are simple step.
Below code snippet may help you.
// parse json to java
Object obj = parser.parse(s);
JSONObject json = (JSONObject) obj;
JSONObject o = (JSONObject) json.get("config");
//get json array.
JSONArray array = (JSONArray) o.get("valueColumns");
System.out.println(array.toJSONString());
//access element by index
System.out.println(array.get(0));

Categories