I have a JSON file which I read from a location and converted it into string as below i.e. A string variable contains exact same JSON as printed below. For some testing purpose I needed it.
So the thing is that I want to update the value of key "MainId". How do I do that?
Here is mine JSON:
{
"Entity": {
"MainId":"XFG",
"AlternateIdentifiers" : [
{
"Type":{
"Abbreviation":"ReferenceNumber"
},
"Value":"abc"
}
]
}
}
Initialize a JSONObject , you have to import the json.org library , put the json in a string and then in the constructor of JSONObject.
So you can navigate the JSON through this new object.
Related
I am trying to do JSON parsing. The JSON data is shown below, I am trying to get the "categories". I was able to JSON parse everything else, but I am not sure what does this "categories" belong to, is it a JSONObject, JSONArray, or something else? I am a newbie and self-taught, usually I am familiar that JSONArray has form of "JSONArray": {["content"]}, and the "content" is JSONObject. But in this case, "categories":["content"]. I am trying to parse this "categories", and turn it to string. Thank you for your help.
{
"results": [
{
"type": "Restaurant",
"id": "jfhuiewjkfkdljiahueijkfnlsdiejkl1484391hjk8421k",
"score": 99.9844207764,
"dist": 15.581982823437135,
"info": "search:ta:840369014527642-US",
"poi": {
"name": "RoofTop Bar",
"categorySet": [
{
"id": 184729472943
}
],
"categories": [
"pub food",
"restaurant"
]}
}]
}
This is what I have tried:
groups = new JSONArray();
groups = response.getJSONArray("results");
if (groups.length() > 0) {
JSONObject resultObject = groups.getJSONObject(0);
if (resultObject.has("poi")) {
if (resultObject.getJSONObject("poi").has("name")) {
nameResult = resultObject.getJSONObject("poi").getString("name");
} else {
nameResult = "Information is not available.";
}
if (resultObject.getJSONObject("poi").has("categories")) {
JSONObject categoriesResult;
categoriesResult = resultObject.getJSONObject("categories").toString();
}
results is an array of objects
The first object contains a property called poi
poi contains a property called categories
So using the top to bottom approach, we can arrive at
const categoriesArray = results[0].poi.categories; // gives categories as an array of strings
const categoriesString = categoriesArray.join(",") // gives categories as string, with comma separated values
I am not sure if it is the actual raw data but the poi object where the categories are contained is malformed. It is missing a closing bracket which could be causing parsing issues.
That apart, the field categories from the poi object is a list of strings I am not sure how you want to format it to a string but you could loop through them and do want you want with them.
In order to obtain them you can access them from your object with results[0].poi.categories or loop through the results before accessing the categories with result.poi.categories where result is the variable containing the currently looped result.
EDIT:
From your code sample, assuming response is a JSONObject you can do the following.
Then to obtain categories in a string without the array format, you can loop through the categories and concatenate them to a string.
String categories = resultObject.get("categories").join(", ");
I have same query. My JSON is as below.
String json="{ "credentials": { "password": "Password"123", "emailAddress": "skylineadmin#gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"
key = password and value is "Password"123" it contains " (double quote).. I am not able to create a java object from this json as it is invalidated.
Gson gson = new Gson();
gson.fromJson(json, PasswordResetDetails.java);
Above code snippet is not Working.
If you are doing this for learning / testing purpose all you need to do is escaping the double quote using :
String json="{ "credentials": { "password": "Password\"123", "emailAddress": "skylineadmin#gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"
If this is a real scenario then I would like to suggest to change the source in order to make sure it provides valid JSON.
There are countless possibilities to check if your JSON is valid (JSON linting), here's one.
I am using JsonPath to retrieve a value from a JSON file. The JSON file looks something like this:
[
{
"username": "John",
"password": {
"passwordValue": "passwordjohn",
"secret_key": "123"
}
},
{
"username": "Nick",
"password": {
"passwordValue": "XXX",
"secret_key": "ZZZ",
"other_key": "YYY"
}
}
]
The JsonPath I am using is to retrieve the password from a particular user. Example:
fun getPassword() {
val passwords: JSONArray = read(jsonFile, "\$.[?(#.name==\"John\")].password")
}
However, I found two obstacles. Firstly, I get back a net.minidev.json.JSONArray always, and the same path with appended [0] doesn't work.
Therefore, I try to get the only element from the JSONArray I get back, like this: credentials[0]. Unfortunately, this removes the double quotes in the field names, resulting in something like this:
{passwordValue: passwordjohn, secret_key: 123}
Which is impossible to work with.
I am looking for a way to get this back:
{"passwordValue": "passwordjohn", "secret_key": "123"}
What I ended up doing was to remove the [ and ] symbols from the beginning of the JSONArray after converting it to a String:
private fun JSONArray.toCredentialString(): String {
val credentialString = this.toString()
return credentialString.substring(1, credentialString.length - 1)
}
Any better solution is welcome.
I am having a Json file.
It contains Nested objects, I am trying to retrieve nested objects by u
Use jsonschema2pojo for generating Java Classes for your Json and then you can use :
String response = "Your full json here";
TestSuiteResponseRO testSuiteRO = new ObjectMapper().readValue(response, TestSuiteResponseRO.class);
You JSON seems invalid..here is valida JSON..post your code if below JSON does not work..
{
"TestSuite": {
"TestSuiteInfo": { "-description": "parse" },
"TestCase": [
{
"TestCaseData": {
"-sequence": "sequential",
"-testNumber": "2",
"-testCaseFile": "testcase\\Web\\Ab.xml"
}
},
{
"TestCaseData": {
"-sequence": "sequential",
"-testNumber": "3",
"-testCaseFile": "testcase\\Web\\BC.xml"
}
}
]
}
}
1.I have removed '}' on of line 22..
2.I have swapped brackets of line 19 and 20..
I'm using the package org.json to parse a JSONArray (I have the json strings saved in a database). However, I don't succeed in parsing it when the same key could have associated a String or a JSONObject, depending on the context.
For example, see the following JSON code...
[ { "cssClass" : "input_text",
"required" : "undefined",
"values" : "First Name"
},
{ "cssClass" : "checkbox",
"required" : "undefined",
"title" : "What's on your pizza?",
"values" : { "2" : { "baseline" : "undefined",
"value" : "Extra Cheese"
},
"3" : { "baseline" : "undefined",
"value" : "Pepperoni"
}
}
}
]
In the code above, the key "values" has 2 possibilities...
A String with value "First Name"
A JSONObject with value {"2":{"value":"Extra Cheese","baseline":"undefined"},"3":{"value":"Pepperoni","baseline":"undefined"}}.
How am I able to process this correctly when the value could be 2 different data types?
You'll probably still need to detect whether it is a JSONObject or a String, so that you can process it further, but perhaps something here might help...
You could try something like this...
String cssClass = myJson.getString("cssClass");
if (cssClass.equals("input_text")){
// Read it as a String
String values = myJson.getString("values");
}
else if (cssClass.equals("checkbox")){
// Read it as a JSONObject
JSONObject values = myJson.JSONObject("values");
// further processing here
}
Or maybe something like this...
String cssClass = myJson.getString("cssClass");
String values = myJson.getString("values");
if (cssClass.equals("input_text")){
// do nothing - it's already a String
}
else if (cssClass.equals("checkbox")){
// Parse the String into a JSONObject
JSONObject valuesObject = new JSONObject(values);
// further processing here
}
Think it this way in js or java duplicate variable creation under same scope is invalid,so to avoid ambiguity put them in separate json object with different variable names before putting it to the json array.