Reading the array name itself (not its content) from JSON using java - java

I have a JSON like this -
result = [
{ "value1": [
{
"number" : "3",
"title" : "hello_world"
},
{
"number" : "2",
"title" : "hello_world"
}
]
},
{ "value2": [
{
"number" : "4",
"title" : "hello_world"
},
{
"number" : "5",
"title" : "hello_world"
}
]
}
]
I want to get result[0] i.e "value1" and result[1] i.e "value2".
Below is my code for parsing this Json -
JsonParser jsonParser = new JsonParser();
JsonArray resultArray = jsonParser.parse(result.getAsJsonArray("result"));
Above code is working fine and I am getting 2 Json arrays. Now for getting value1 I have written this code-
String v = resultArray.get(0).getAsJsonObject().get("value1").getAsString();
But this is not giving me value1 rather than its throwing error "java.lang.IllegalStateException". What I am doing wrong here?
Please note that I want to read array name of "value1" and "value2" itself as string and not its inside content.Means print line should print value1 as output.

Value1 is not String but rather a JsonArray,
when you call getAsString() method, it will throw Exception telling you the value is not of a String object.
few Options :
1- read the value as JsonArray then convert it to String using toString method:
String v = resultArray.get(0).getAsJsonObject().getAsJsonArray("value1").toString();
2- use toString method directly on JsonElement itself (return value of get("value1")
String v = resultArray.get(0).getAsJsonObject().get("value1").toString();
I normally use option one because it enforces the check.
EDIT:
After reading comment, basically what is required is to get all the keys of each JsonObject within each Object
you need to loop through the array and get all they entrySet().(not tested but should work)
for(JsonElement element : resultArray){
JsonObject next= element.getAsJsonObject();
for(Map.Entry<String,JsonElement> entry : next.entrySet()){
System.out.println(entry.getKey()); // <-- prints out value1 and value2
}
}

Related

How to get a list from a JsonArray of objects

I would like to convert the response.getBody of above call to array.
I am trying to parse only the array "data" of json as list.
JSON:
{
"totalValue": 21,
"data": [
{
"id": 1,
"firstname": "Tom",
"lastname":"Pit"
},
{
"id": 2,
"firstname": "Jim",
"lastname":"Sol"
}
]
}
So after some tries i reach here:
JSONParser parser = new JSONParser();
Object obj = (Object) parser.parse(response.getBody());
JSONArray array = new JSONArray();
array.add(obj);
This array has size: 1 in the array there is a json object with 2 values first is long value of the total value (21) second is JsonArray with value : all the values and key "data" .
I would like to parse the JsonArray as list of object in java...but whatever to try get the error most of the times.....
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column
Any help?
If you want to parse the "data" as list of object in java you can try with:
Map<?, ?> mapResponse = response.getBody();
List<?> data = (List<?>)mapResponse.get("data");
I hope this help you.

Parsing nested json array in 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

jsonArray.length() not given the right number of array element

I am using org.json parser.
I am getting a json array using jsonObject.getJSONArray(key).
The problem is the jsonArray.length() is returning me 1 and my json array have 2 elements, what am I doing wrong?
String key= "contextResponses";
JSONObject jsonObject = new JSONObject(jsonInput);
Object value = jsonObject.get("contextResponses");
if (value instanceof JSONArray){
JSONArray jsonArray = (JSONArray) jsonObject.getJSONArray(key);
System.out.println("array length is: "+jsonArray.length());/*the result is 1! */
}
Here is my json:
{
"contextResponses" : [
{
"contextElement" : {
"type" : "ENTITY",
"isPattern" : "false",
"id" : "ENTITY3",
"attributes" : [
{
"name" : "ATTR1",
"type" : "float",
"value" : ""
}
]
},
"statusCode" : {
"code" : "200",
"reasonPhrase" : "OK"
}
}
]
}
The result is perfectly normal, since the JSONArray contains only one JSONObject. To get the length of the JSONObject you're looking for, use this:
// Get the number of keys stored within the first JSONObject of this JSONArray
jsonArray.getJSONObject(0).length();
//----------------------------
{
"contextResponses" : [
// The first & only JSONObject of this JSONArray
{
// 2 JSONObjects
"contextElement" : {
// 1
},
"statusCode" : {
// 2
}
}
]
}
Your array contains exactly one object therefore the length is correct:
"contextResponses" : [
{
... content of the object ...
}
]

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

JSON: parsing with java and org.json (recursion)

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.

Categories

Resources