Handler Error: When inserting JSONObject in a JSONArray (JAVA) - java

I have the following JSON Data, with hits having multiple recipe objects
"hits": [
{
"recipe": {
"uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_b79327d05b8e5b838ad6cfd9576b30b6",
"label": "Chicken Vesuvio",
"image": "https://www.edamam.com/web-img/e42/e42f9119813e890af34c259785ae1cfb.jpg",
"source": "Serious Eats",
"url": "http://www.seriouseats.com/recipes/2011/12/chicken-vesuvio-recipe.html",
"shareAs": "http://www.edamam.com/recipe/chicken-vesuvio-b79327d05b8e5b838ad6cfd9576b30b6/chicken",
"yield": 4,
However, I'm trying to get all the recipe objects which are children elements of hits
Using this code
JSONArray recipeArray = null;
JSONObject json = new JSONObject(jsonString); //initial JSONObject (See explanation section below)
JSONArray results = (JSONArray) json.get("hits");
for(int i = 0; i < results.length(); i++){
JSONObject resultObject = (JSONObject) results.get(i);
JSONObject recipeobj = (JSONObject) resultObject.get("recipe");
recipeArray.put(recipeobj);
}
During runtime, recipeArray.put gives a handler exception.
I have tried several methods on trying to do this such as looping the following
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONArray("hits");
JSONObject item = jsonArray.getJSONObject(i); JSONArray
JSONArray recipeArray = item.getJSONArray("recipe");
But gives a conversion error during the last line.
Any help or suggestions would be appreciated.

As your inner recipe object is not an array, it will throw JSONException for this
JSONArray recipeArray = item.getJSONArray("recipe");
And in your initial approach, recipeArray is not initialized which would have caused you NPE.
you can do like this
JSONArray recipes = new JSONArray();
JSONArray jsonArray = jsonObject.getJSONArray("hits");
for (int i=0; i< jsonArray.length(); i++){
JSONObject item = jsonArray.getJSONObject(i);
JSONObject recipe = item.getJSONObject("recipe");
recipes.put(recipe);
}

Related

Unable to create same parameter value twice in json array

In this code, I am trying to creating something like this-
public String KLYA_JSON_LookUp_MultiNode(String KLYA_To,String KLYA_DLRURL,String KLYA_To2) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("dlrurl", KLYA_DLRURL);
JSONArray array = new JSONArray();
JSONObject Array_item = new JSONObject();
Array_item.put("to", KLYA_To);
Array_item.put("to", KLYA_To2);
array.add(Array_item);
jsonObj.put("lookup", array);
CreatedJson = jsonObj.toString();
System.out.println(CreatedJson);
return CreatedJson ;
}
Output:
{"lookup": [{
"to": "890XXXXXXX"
}, {
"to": "890XXXXXXX"
}], "dlrurl": "http://www.example.com/dlr.php/......"
}
but I dont get as per the above comment, it ends up printing only one to in the array where as it should print two.
Insert
array.add(Array_item);
Array_item = new JSONObject();
between the two calls to Array_item.put.
So after Thomas and Petter's suggestion, I worked on it and this is how it got resolved.
JSONObject jsonObj = new JSONObject();
JSONArray array = new JSONArray();
JSONObject Array_item = new JSONObject();
JSONObject NextArray_item = new JSONObject();
jsonObj.put("dlrurl", "url");
NextArray_item.put("to","XXXX");
Array_item.put("to", "XXX");
array.add(Array_item);
array.add(NextArray_item);
jsonObj.put("lookup", array);
CreatedJson = jsonObj.toString();
System.out.println(CreatedJson);

Nested array for org.json

I tried to build the nested array for the following json blob using jsonobject and jsonarray. For some reason, the object is failing. Any thoughts - please, how best we can put this format.
{
"reporter_desc": "pot",
"timestamp": "1487830751",
"incidents": [
{
"src_ip": 822382162,
"exploit": "scan",
"incident_type": 3,
"occurred": "1487830751",
"description": "pot scan"
}
Here is the JSONObject and JSONArray :
JSONObject object = new JSONObject();
object.put("reporter_desc", "mtpot");
object.put("timestamp", "1487830751");
JSONArray array = new JSONArray();
JSONObject arrayElement = new JSONObject();
arrayElement.put("src_ip", 822382162);
arrayElement.put("exploit", "scan");
arrayElement.put("incident_type", 3);
arrayElement.put("occurred", "1487830751");
arrayElement.put("description", "pot vulnerability scan");
array.put("incidents");
object.put("incidents", array);

How to acummulate data in JSON?

I extract some data from a database and I want to create a JSON based on this data. The JSON must look like this:
Ducument1: {
documentDescription: "some description1"
idTask: 49
idDocument: 1
documentFilepath: "D:\workspace\docs"
}
Ducument2: {
documentDescription: "some description2"
idTask: 49
idDocument: 2
documentFilepath: "D:\workspace\"
}
I tried several things, but they didn`t work. Such as:
public JSONObject get(){
TaskDocumentEntity document = new TaskDocumentEntity();
JSONObject childJson = new JSONObject();
JSONArray arrayJson = new JSONArray();
JSONObject parentJson = new JSONObject();
for(int i=0;i < taskDocumentRepository.getCountDocs();i++){
jo.put("idTask",taskDocumentRepository.getAllDocumentsByIdTask().get(i).getIdTask());
jo.put("documentDescription",taskDocumentRepository.getAllDocumentsByIdTask().get(i).getDescriere());
jo.put("documentFilepath",taskDocumentRepository.getAllDocumentsByIdTask().get(i).getFilepath());
ja.add(jo);
mainObj.put(i,ja);
}
since you don't tell us what doesn't work, so I just assume things:
it is most likely the problem is having your JsonObject and Jsonarrays in wrong places relative to your loop.
try this:
JSONArray ja=new JSONArray();
for(int i=0;i < taskDocumentRepository.getCountDocs();i++){
JSONObject jo=new JSONObject();
JSONObject mainObj=new JSONObject();
jo.put("idTask",taskDocumentRepository.getAllDocumentsByIdTask().get(i).getIdTask());
jo.put("documentDescription",taskDocumentRepository.getAllDocumentsByIdTask().get(i).getDescriere());
jo.put("documentFilepath",taskDocumentRepository.getAllDocumentsByIdTask().get(i).getFilepath());
mainObj.put(i,jo);
ja.add(mainObj);
}
NOTE:
where I initiated jo and ja and mainObj also I put mainObj outis
object creation wrong
JSONArray ja=new JSONArray();
for(int i=0;i < taskDocumentRepository.getCountDocs();i++){
JSONObject jo=new JSONObject();
JSONObject mainObj=new JSONObject();

Creating JSONArray from JSONObjects

I have json libs (json-simple) and trying to make jsonarray from jsonobjects.
My aim to make JSON string look something like string below
[{"name": "somename","surname": "somesurname"},
{"name": "somename2","surname": "somesurname2"}]
and it will have possibility of adding new objects in the same array.
This what im "hardcoding" now.
JSONObject obj= new JSONObject();
JSONArray arr = new JSONArray();
for(int i = 0 ; i< arr.size() ; i++)
{
obj.put("name", name);
obj.put("surname", surname);
arr.add(obj);
obj= new JSONObject();
}

Issue With JSON Object in Java?

I have a JSON Object which converted into String and saved into database .But when i am trying to get it back it is throwing exception.My object is something like that...
{"COLUMN":["Type","Sub Type","F.P.","P.P.","Process","Due To Start"]}
How can we get the data back in Normal form?
My Java Code is.....
JSONObject obj = new JSONObject();
JSONArray the_json_array = obj.getJSONArray(userReorderOption);
int size = the_json_array.size();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
arrays.add(another_json_object);
}
And Exception i am getting....
net.sf.json.JSONException: JSONObject["{\"TASKLIST_COLUMN_REORDER\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}"] is not a JSONArray.
And this is java Code how i am creating JSON Object and saving into database...
String userReorderSelection;
Set set = new LinkedHashSet(userReorderSelection);
JSONObject json = new JSONObject();
json.accumulate("COLUMN", set);
saveJSONObj("PrimaryKeyColumn", json.toString());
Thanks Tichodroma,
But as i told i am using net.sf.json.JSONObject class and above things we can achieve from this class too..What i did to solve the above issue?...Please have a look on the Java code...
JSONObject jsonObj = new JSONObject();
JSONObject obj = jsonObj.fromObject(userReorderOption);
JSONArray columnName = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < columnName.size(); i++) {
System.out.println(columnName.getString(i));
}
This code work fine for me with my Json Jar**(net.sf.json)**
Your JSON is not a JSONArray.
A JSONArray is an ordered sequence of values.
You have a JSONObject.
A JSONObject is an unordered collection of name/value pairs.
Edit:
Using the JSON implementation from org.codehaus.jettison.json, you can do this:
String json = "{\"COLUMN\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}";
JSONObject obj = new JSONObject(json);
JSONArray column = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < column.length(); i++) {
final String field = column.getString(i);
System.out.println(field);
}
Result:
Type
Sub Type
F.P.
P.P.
Process
Due To Start

Categories