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..
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 need to modify a particular value of a key in my json file, it is a nested JSON file and i have traversed till that key value pair but i'm not able to modify the value and don't know how to write back to the json.
Using json-simple to parse the JSON
This is the JSON file:
{
"entity": {
"id": "ppr20193060018",
"data": {
"relationships": {
"productpresentationtolot": [
{
"id": "",
"relTo": {
"id": "",
"data": {
"attributes": {
"rmsitemid": {
"values": [
{
"source": "internal",
"locale": "en-US",
"value": "2019306"
}
]
}
}
},
"type": "lot"
}
}
]
}
},
"type": "productpresentation"
}
}
Reading it using below code:
JSONParser parser = new JSONParser();
reader = new FileReader("path.json");
JSONArray rmsArray =(JSONArray) rmsitemid.get("values");
for(Object obj2:rmsArray)
{
JSONObject tempObj1=(JSONObject)obj2;
System.out.println(tempObj1.get("value"));
}
I'm able to print what is there in value(Key) i.e., 2019306 but i don't have any idea how can i replace it with some other value and it should change the value in JSON file also.
Any help appreciated!
Here is a complete exmaple how to read and write using the simple-json library:
// read from resource file
JSONObject value;
try (Reader in = new InputStreamReader(getClass().getResourceAsStream("/simple.json"))) {
JSONParser parser = new JSONParser();
value = (JSONObject) parser.parse(in);
}
JSONObject entity = (JSONObject) value.get("entity");
// update id
entity.put("id", "manipulated");
// write to output file
try (Writer out = new FileWriter("output.json")) {
out.write(value.toJSONString());
}
The JSONObjects are basically Maps. So you can just put values inside.
In order to create a JSON string again, use toJSONString().
In my example, I create a new output file. You could also override the original input file, though. But you have to write the file completely.
*I am already getting this JSON object from responce.body(). I want every data inside this separately in variable. I am using java.
{
"Classes":{
"Primary":{
"Classes":{
"1":{
"section":[
"a",
"b"
]
},
"2":{
"sections":[
"a",
"b"
]
}
}
}
}
}
*I know how to get the JSONObject but i dont know how can i get that array inside "section". even if i get that array with JSONArray then how to convert it to JSONObject? or String.
*Note that inside value of "section" array is dynamic, value inside that array is dynamic and can be multiiple from "a" to "z". Also JSONObject inside "Classes"(inside primary) is also dynamic. there can be dynamic and multiple "1","2"... and it is string, It is not necessary that there will be incremental numbers.
After 30 mins of war, I find out your answer just copy this code and paste where you want to use -
Here it is -
String json = "{
"Classes": {
"Primary": {
"Classes": {
"1": {
"section": [
"a",
"b"
]
},
"2": {
"sections": [
"a",
"b"
]
}
}
}
}
}";
try {
JSONObject jsonObject = new JSONObject(json);
Log.d("jsonObj", jsonObject.toString());
JSONObject classJsonObj = jsonObject.optJSONObject("Classes");
JSONObject primaryJsonObj = classJsonObj.optJSONObject("Primary");
JSONObject internalClassJsonObj = primaryJsonObj.optJSONObject("Classes");
if(internalClassJsonObj != null){
int i = 1;
JSONObject dynmaicInternalJsonObj = null;
while (true){
dynmaicInternalJsonObj = internalClassJsonObj.optJSONObject(i+"");
if(dynmaicInternalJsonObj != null){
JSONArray sectionJsonArr = dynmaicInternalJsonObj.optJSONArray("sections");
Log.d("SectionArr", sectionJsonArr.toString());
// Finally you got your section data here...
if(sectionJsonArr != null){
for(int j=0; j<sectionJsonArr.length(); j++){
System.out.println("Dynamic Sections Data is: - " + sectionJsonArr.opt(j));
}
System.out.println("\n\n");
}
}else{
break;
}
i++;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You've tagged this as java so I can only assume you want a solution for that language.
To use this data it needs to parsed, this means you are converting the data into a more usable type.
Click this to learn how to parse JSON in java
Assuming you need solution in java, use this to get a object classes for your json structure and then convert your json to java objects using libraries like GSON.
Example:
String json = "{\"city\":\"San Jose\", \"state\": \"CA\", \"country\":\"USA\"}";
Gson gson = new Gson();
Place place = gson.fromJson(json, Place.class);
If you are using ionic (typescript or javascript), you can use the below approach
var json = "{
"Classes": {
"Primary": {
"Classes": {
"1": {
"section": [
"a",
"b"
]
},
"2": {
"sections": [
"a",
"b"
]
}
}
}
}
}";
for(let item in json.Classes.Primary.Classes){
console.log(item.sections);
}
If you want to display the same data in frontend using html, use *ngFor
<div *ngFor="let item in json.Classes.Primary.Classes ">
<h5>{{item.sections}}</h5>
</div>
I hope it helps.
I am getting an error JSONObject["results"] not found when trying to parse the below json string:
{
"serviceModel": {
"results": [
{
"application": {
"applicationId": 1234"applicationStatus": "Determined""applicationSubmittedDate": "2013-09-19 12:00:00 AM""applicationType": "Initial""asOfDate": "2018-12-28 02:42:26 AM""logicalApplicationId": "1234"
}"contact": {
"addresses": [
{
"city": "Bridgeport""county": "Fairfield""line1": "123 Main Road""state": "CT""type": "H""zipCode": "12345"
}{
"city": "Bridgeport""county": "Fairfield""line1": "123 Main Road""state": "CT""type": "M""zipCode": "12345"
}
]"dob": "1900-01-01""firstName": "John""gender": "MALE""homelessIndicator": "N""lastName": "Smith""otherIds": []"personId": "11233""preferredLanguage": "E""primaryApplicantIndicator": "Y""ssn": "123456789"
}
}
]"summary": {
"resultCount": 1
}
}
}
And below is my current code (although I have tried many different iterations):
JSONObject jsonResults = new JSONObject(sb.toString());
JSONArray array = jsonResults.getJSONArray("results");
for (int index=0;index<array.length();index++)
{
JSONObject obj=array.getJSONObject(index);
if (!obj.isNull("ssn"))
}
ssn = obj.getString("ssn");
data.addToLog("SSN"+ String.valueOf(index),ssn);
}
}
data.addToLog("SSN",ssn);
Any help is appreciated!
Your string is not in valid JSON format, as you are not using comma separators between fields. Change your json string to like below and then try.
{"serviceModel":{"results":[{"application":{"applicationId":1234,"applicationStatus":"Determined","applicationSubmittedDate":"2013-09-19 12:00:00 AM","applicationType":"Initial","asOfDate":"2018-12-28 02:42:26 AM","logicalApplicationId":"1234"},
"contact":{"addresses":[
{"city":"Bridgeport","county":"Fairfield","line1":"123 Main Road","state":"CT","type":"H","zipCode":"12345"},
{"city":"Bridgeport","county":"Fairfield","line1":"123 Main Road","state":"CT","type":"M","zipCode":"12345"}],
"dob":"1900-01-01","firstName":"John","gender":"MALE","homelessIndicator":"N","lastName":"Smith",
"otherIds":[],
"personId":"11233",
"preferredLanguage":"E",
"primaryApplicantIndicator":"Y",
"ssn":"123456789"
}}],"summary":{"resultCount":1}}}
your json string is not well formatted, missing some comma and quote,
can use this one :
{"serviceModel":{"results":[{"application":{"applicationId":"1234","applicationStatus":"Determined","applicationSubmittedDate":"2013-09-19 12:00:00 AM","applicationType":"Initial","asOfDate":"2018-12-28 02:42:26 AM","logicalApplicationId":"1234"},"contact":{"addresses":[{"city":"Bridgeport","county":"Fairfield","line1":"123 Main Road","state":"CT","type":"H","zipCode":"12345"},{"city":"Bridgeport","county":"Fairfield","line1":"123 Main Road","state":"CT","type":"M","zipCode":"12345"}],"dob":"1900-01-01","firstName":"John","gender":"MALE","homelessIndicator":"N","lastName":"Smith","otherIds":[],"personId":"11233","preferredLanguage":"E","primaryApplicantIndicator":"Y","ssn":"123456789"}}],"summary":{"resultCount":1}}}
to get json array results can do :
JSONArray array = jsonResults.getJsonObject("serviceModel").getJsonArray("results");
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.