Parsing nested json array in java - java

I have json file in below format.
{
"data":[
{
"prjId": 1,
"name" : "Forj1",
"issue": [
{
"id": 00001,
"status" : "Closed"
},
{
"id": 00002,
"status" : "Open"
}
]
},
{
"prjId": 2,
"name" : "Forj2",
"issue": [
{
"id": 00003,
"status" : "Closed"
},
{
"id": 00004,
"status" : "Open"
}
]
}],
"issueCounter": 7,
"success": true
}
Here "data" is array of projects, and within project attribute there is array of "issue".
So far if I remove "issue" array, I am able to traverse the json to one level down in "data" attribute, If this json has "issue" array I get an error saying missing comma.
javax.json.stream.JsonParsingException: Invalid token=NUMBER at (line no=15, column no=14, offset=242) Expected tokens are: [COMMA]
Below is the code that I have right now. I have two problems with this, one is the error while reading if I place the "issue" attribute, and secondly a way to read the "issue" array and traverse all attributes within.
InputStream fis = new FileInputStream(pathToFile+"data3.json");
JsonReader jsonReader = Json.createReader(fis);
//the error is thrown on below line while reading the above json.
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
fis.close();
System.out.println(jsonObject.getInt("issueCounter"));
//reading arrays from json
JsonArray jsonArrayData = jsonObject.getJsonArray("data");
Project [] prj = new Project[jsonArrayData.size()];
int index = 0;
for(JsonValue value : jsonArrayData){
JSONObject jsonObj = new JSONObject(value.toString());
System.out.println(jsonObj.getString("name"));
System.out.println(jsonObj.getInt("prjId"));
//this is also the place where I am stuck, I know I need to construct an array out of it by obtaining issue attribute. Below is very very wrong.
/*
JsonArray jsonArrayIssue = jsonObj.getJsonArray("issue");
for(JsonValue issue : jsonArrayIssue){
JSONObject jsonIssueObj = new JSONObject(issue.toString());
System.out.println(jsonIssueObj.getString("status"));
System.out.println(jsonIssueObj.getInt("id"));
}
*/
}
Any help or pointers is deeply appreciated. I can tweak the json if its required ultimately I need to maintain an array of issues.

The problem as others said is the JSON.
"id": 00001 <-- this is a number, numbers cannot start with a leading zero as per JSON stadard.
If you control the JSON you should tweak it.
Alternatively ff you don't, you can use a less strict parser like org.json.simple https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
The code will be the same as yours, just adjusted to org.json.simple
try { ...
JSONObject rootJSON = (JSONObject) new JSONParser().parse(jsonString);
JSONArray dataList = (JSONArray) rootJSON.get("data");
for(Object projectObj: dataList.toArray()){
JSONObject project = (JSONObject)projectObj;
JSONArray issueList = (JSONArray) project.get("issue");
for(Object issueObj: issueList.toArray()){
JSONObject issue = (JSONObject) issueObj;
//do something with the issue
}
}
} catch (ParseException e) {
//do smth
e.printStackTrace();
}

Your json data is invalid.You can check here.
http://jsonlint.com
...issue": [{ "id": 00001,
"status": ----------------------^
Your id must be string number,string,boolean.Send 1,2,3,.... as return values and check if it works.

Your code looks okay the problem is the JSON formatting. Specifically the following lines:
"id": 00001,
"id": 00002,
"id": 00003,
"id": 00004,
Basically if you want it in that format you will need to set them as strings by wrapping the values in quotations i.e. "id": "00001" or you can use a valid number i.e. "id": 1

Related

What is the best way to extract a value without having a Java Object class

I have a string like below
{
"id": "abc",
"title": "123.png",
"description": "fruits",
"information": [
{
"type": "apple",
"url": "https://apple.com"
},
{
"type": "orange",
"url": "https://orange.com"
}
],
"versions": 0
}
I want to get the value of url where type: orange. The list in information may not always be in same order as appearing in the data above. I know I could do it easily in python with json.loads and json.dump.
I am trying to do it java using JsonNode and objectMapper.readTree.at("/information") but I am unable to get past this point in a clever neat way to get the list and fetch the url where type = orange.
This is pretty straightforward
Use a JSON library and parse the response using the library. Then get only the values and attributes that you need...
Example relevant to your case:
// Get your Json and transform it into a JSONObject
JSONObject mainObject = new JSONObject(yourJsonString); // Here is your JSON...
// Get your "information" array
JSONArray infoArray = mainObject.getJSONArray("information"); // Here you have the array
// Now you can go through each item of the array till you find the one you need
for(int i = 0 ; i < infoArray.length(); i++)
{
JSONObject item = participantsArray.getJSONObject(i);
final String type = item.getString("type");
final String url = item.getString("url");
if(type.equals("orange"))
{
// DO WHATEVER YOU NEED
}
}

Java: Array of Arrays from JSON

I have a JSON Arrays of Array like this
"results": [
{
"id": "AAA",
"color": "#4D4837",
"links": {
"self": "https://aaa.com",
"html": "https://bbb.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3891,
},
{
"id": "BBB",
"color": "#4D453",
"links": {
"self": "https://abb.com",
"html": "https://bcc.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3000,
}
]
And I would like to retrieve "https://bbb.com" and "https://bcc.com" of "html", but I don't know how to do that.
Based on kindly comment, I put the following.
somehow, "getJSONObject()"can not be put. The error message says "Cannot resolve method 'getJSONObject' in 'JSONArray'".
JSONArray array = new JSONArray((Collection) jobjt.get("Strings"));
for (int i =0 ; i<2 ; i++){
JSONObject job = (JSONObject) array.get(i); --> get(i) can not be changed to getJSONObject(i)
String id = job.get("id").toString();
String color = job.get("color").toString();
String photoUrl = job.get("links").toString(); --> By updating here, I want to store only "https://bbb.com" and "https://bcc.com".
}
But when I tried to use the following, not only "html", but "self" and the other information are retrieved.
String photoUrl = job.get("links").toString();
Please tell me how to retrieve only "html".
I am using IntelliJ.
Steps to be followed(assuming you have proper JSONArray you mentioned):
get JSONObject from your JSONArray by index ie. for your case, index=0 here
Get the inner JSONObject by key of links
Now, access your content by key of html
Example for your case:
JSONObject indexedObject = jsonArray.getJSONObject(0);
JSONObject linksObject = indexedObject.getJSONObject("links");
String html= linksObject.getString("html");
Better keep checking if key exists as Harshal suggests

parse JSON to grab 'name' from an array

I'm trying to grab the 'name' from the JSON snippet I've included. I have tried the following but what I'm expecting is never grabbed.
Edit: 'output' is the full JSON string in case it wasn't already understood ;)
JSONObject result = null;
JSONArray data = null;
try {
try {result = new JSONObject(output);} catch (JSONException e) {e.printStackTrace();}
try {
data = result.getJSONArray("data");
for(int a=0;a<data.length();a++){
System.out.println(result.getJSONObject(String.valueOf(a)).getString("name"));//getJSONObject("results")
}
Here is the JSON snippet I'm trying to work with:
{
"code": 200,
"status": "Ok",
"copyright": "© 2015 MARVEL",
"attributionText": "Data provided by Marvel. © 2015 MARVEL",
"attributionHTML": "Data provided by Marvel. © 2015 MARVEL",
"etag": "b130a8b7af591e4e7ca078753f9c5c8a76e55e5d",
"data": {
"offset": 0,
"limit": 20,
"total": 1485,
"count": 20,
"results": [
{
"id": 1011334,
"name": "3-D Man",
"description": "",
"modified": "2014
.
.
.
.
.
.
.
.
.
.
To get you started, "data" points to a JSON Object, not array. So it should be:
data = result.getJSONObject("data");
Then, "results" points to a JSON array:
JSONArray results = data.getJSONArray("results");
Then you can try your loop. You shouldn't be turning a into a String - getJSONObject() takes an int for the index.
In case you're confused between Objects and Arrays, a JSON object has key - value pairs and are enclosed in curly braces. The keys are strings and the values can be a mix of any type:
{"key1": 5, "key2": "value2", "key3": {
"anotherObject": [1,2,3,4]
}
}
An array is a list of objects and is enclosed in square brackets:
[{...}, {...}, {...}]
The elements in the list don't have to be JSON objects, and in good JSON they will all be of the same type:
[1,2,3,4,4] or ["we", "are", "in", "an", "array"]
JSONTokener jsonTokener = new JSONTokener(jsonVaule);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
Int code =jsonObject.getInt("code");
String status =jsonObject.getString("status");
//{obejcet,obejcet,...}
for data{} is the same way~
JSONObject dataJsObject = (JSONObject) jsonObject.getJsonObject("data");
int offset =dataJsObject.getInt(""iffset);
....
//[{},{}] this type is jsonArrary
JSONArray results = dataJsObject.getJSONArray("results");
for(JSONObject resultJsonObj:JSONArray){
Int id =jsonObject.getInt("id");
//...and so on
}
hope it can help you~
You can parse like that
JsonObject obj = new JsonObject(StringResponse);
String code = obj.getString(code);
//same way you can get other string
JsonObject obj1 = obj.getJsonObject(Data);
String offset= obj.getString(offset);
//same way you can get other string
JsonArray jsonarr = obj1.getJsonArray(results);
for(i=0;i< jsonarr.size(); i++){
JsonObject innerObj = jsorr.getJsonObject(i);
String id= obj.getString(id);
//same way you can get other string
}
Hope It will helpful for you

JSON different objects in an array

At the moment i'm trying to understand json and how it works.
But i have a problem with an array of objects.
all objects in the array have a key called "value" (i know it's weird, it's not my code) what also is an object.
And now to the problem: This object called "value" has always different key-values.
So i dont now how i can parse the json code to java object code, when it differ, every time.
Here some examples:
First object of the array:
"value":
{
"local":
[
"English", "Deutsch", Espanol"
],
"english":
[
"English", "Deutsch", Espanol"
],
},
Second object(now a string, not object) of the array:
"value" : "",
Third object of the array:
"value" : {},
...
Maybe I'm doing the parsing wrong.
First I have created the beans classes in java for the json code and then I'm using the automatic parser of google. (gson)
It works when only one of the examples above is inside the json code. (it should not differ, like changing from string to object...)
Gson gson = new Gson();
Output output = gson.fromJson(json, Output.class);
Output is the main class for the json stuff.
I have found out that maybe while parsing I could check a value called "id" first, and from that I could create another beans class with the right variables ...
Thats the code i need to parse to java objects and how do you do that??
The problem is the key called "value", because its always different.
With my method of using the google parser "gson" it wont work, because i'm getting exception that its an string but i was waiting for an object...
{
"status":"success",
"data":{
"panel":{
"title":{
"label":{ "local":"Tote Selection", "english":"Tote Selection" },
"image":"public/img/pick.jpg", "type":"default"
},
"isFirst":false, // currently not used
"isLast":false, // currently not used
"ownCount":0, // currently not used
"panelsCount":0, // currently not used
"elements":[
{
"type":"text",
"id":"1", "value":{ "local":"Scan next order tote",
"english":"Scan next order tote" },
"label":{ "local":"", "english":"" }, "color":"000000",
"fontsize":18, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "bgcolor":"", "isFocus":false
},
{
"type":"text",
"id":"4", "value":{ "local":"Scan tote: ", "english":"Scan tote: " },
"label":{ "local":"", "english":"" }, "color":"000000", "fontsize":20,
"fontstyle":"strong", "alignment":"left", "rows":"undefined",
"bgcolor":"", "isFocus":false
},
{
"type":"input",
"id":"6", "value":"", "label":{ "local":"", "english":"" },
"color":"000000", "fontsize":24, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "isFocus":true
},
{
"type":"button",
"id":"1", "value":{ "local":"", "english":"" },
"label":{ "local":"Menu", "english":"Menu" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"left",
"rows":"undefined", "isFocus":false
},
{
"type":"button",
"id":"4", "value":{ "local":"", "english":"" },
"label":{ "local":"Enter", "english":"Enter" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"right",18
"rows":"undefined", "isFocus":false
}
]
},
"authToken":"0fdd440a-619f-4936-ab74-d189accb5bd9",
"routing":{
"controller":"panel",
"action":"process",
"workflowId":"singlepicking",
"taskId":"orderSelection"
}
}
}
Thank you for your help!
it looks a little bit different but your answer helped me! Thx
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(br).getAsJsonObject();
//now getting all the json values
String status = obj.get("status").getAsString();
JsonObject data = obj.getAsJsonObject("data");
String authToken = data.get("authToken").getAsString();
JsonObject routing = data.getAsJsonObject("routing");
String controller = routing.get("controller").getAsString();
String action = routing.get("action").getAsString();
String workflowId = routing.get("taskId").getAsString();
If I understood ur question properly u can retrieve the values of the JSONArray as below
for (int i = 0; i < JArray.length(); i++) {
print(JArray.getJSONObject(i).tostring())
}
So if i am right u are getting the JSON from a String First?? so please try below first store the String in JSONObject as JSONObject obj = new JSONObject(str);//str is the string that u are getting
to get the valueenglish that are in data-panel-tittle-label is
String englishinLable=obj .getJSONObject("data").getJSONObject("panel").getJSONObject("title").getJSONObject("label").optString("english")

Extracting data from JSON array

I know its an array, but I am completely new to JSON and need help comprehending how this is structured, here is my attempt at extracting data:
String JSonString = readURL("//my URL is here");
JSONArray s = JSONArray.fromObject(JSonString);
JSONObject Data =(JSONObject)(s.getJSONObject(0));
System.out.println(Data.get("name"));
My JSON data that I have goes like this :
{
"sports": [
{
"name": "basketball",
"id": 40,
"uid": "s:40",
"leagues": [
{
"name": "National Basketball Assoc.",
"abbreviation": "nba",
"id": 46,
"uid": "s:40~l:46",
"groupId": 7,
"shortName": "NBA",
"athletes": []
}
]
}
],
"resultsOffset": 10,
"resultsLimit": 10,
"resultsCount": 1,
"timestamp": "2013-11-18T03:15:43Z",
"status": "success"
}
I dont really have a strong grasp of this stuff so all the help is appreciated.
Here is the idea :
JSONObject root = new JSONObject(yourJsonString);
JSONArray sportsArray = root.getJSONArray("sports");
// now get the first element:
JSONObject firstSport = sportsArray.getJSONObject(0);
// and details of the first element
String name = firstSport.getString("name"); // basketball
int id = firstSport.getInt("id"); // 40
JSONArray leaguesArray = firstSport.getJSONArray("leagues");
// and so on, you can process leaguesArray similarly
It should work (feel free to complain about compile errors if there are any)
Your JSON data is an object (it starts with a curly brace). In the next inner layer, there is a single array (at key "sports"):
String jsonString = readURL("//my URL is here");
JSONObject result = JSONObject(jsonString);
JSONArray sports = result.getJSONArray("sports");
JSONObject sport = sport.getJSONObject(0);
System.out.println(sport.getString("name"));
I might have used another JSON library than you.
JSON means JavaScript Object Notation.
Objects in javascripts are just containers and can be represented by key-value pairs. Please find below notations to understand about json.
Represent objects in json: E.g. Student
{"name" : "Robin", "rollnumber" : "1"}
Represent array in json : E.g. Array of students
[{"name" : "Robin", "rollnumber" : "1"}, {"name" : "Mark", "rollnumber" : "2"}]
You can understand more on JSON from diagrams on this link http://www.json.org/fatfree.html
There are various ways available to to convert JSON to javaobject and javaobject to JSON : One of them is http://wiki.fasterxml.com/JacksonInFiveMinutes
Adding detailed code here along with the imports .
If this helps.
import org.json.JSONException;
import org.json.JSONObject;
public class extractingJSON {
public static void main(String[] args) throws JSONException {
// TODO Auto-generated method stub
String jsonStr = "{\"name\":\"SK\",\"arr\":{\"a\":\"1\",\"b\":\"2\"},\"arrArray\":[{\"a\":\"1\",\"b\":\"2\"}]}";
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("name");
System.out.println(name);
String first = jsonObj.getJSONObject("arr").getString("a");
System.out.println(first);
first = jsonObj.getJSONArray("arrArray").getJSONObject(0).getString("a");
System.out.println(first);
}
}

Categories

Resources