Creating JSONArray from JSONObjects - java

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();
}

Related

Handler Error: When inserting JSONObject in a JSONArray (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);
}

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

converting JSON OBJECT to JSON ARRAY

This is very simple one but struggeling. help me out of this.
I am having a json data { "abc":"test","bed":"cot","help":"me"}
I want to convert above jsonObject into JSON ARRAY like [{ "abc":"test","bed":"cot","help":"me"}]
JSONObject obj= new JSONObject(str.toString());
Iterator x = obj.keys();
JSONArray jsonArray = new JSONArray();
Map<String, String> map = new HashMap<String, String>();
while (x.hasNext()) {
for(int i=0;i<obj.length();i++) {
LOG.info("=============");
String key = (String) x.next();
jsonArray.put(obj.get(key));
}
}
I am getting only values. Please help me solve this.
Directly put JsonObject i.e. obj into jsonArray
jsonArray.put(obj);
//result is [{ "abc":"test","bed":"cot","help":"me"}]
Final code
JSONObject obj= new JSONObject(str);
JSONArray jsonArray = new JSONArray();
//simply put obj into jsonArray
jsonArray.put(obj);
//result is [{ "abc":"test","bed":"cot","help":"me"}]
It works for me.
JSONObject obj = new JSONObject(result.toString());
JSONArray arr = obj.getJSONArray("value");

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();

JSON - Create JSONObject with array

I need to create in a Java (Android) a JSONObject/JSONArray with the exact following structure:
{
"listId":
[
"c02bc683-fcd7-47a5-b157-853e26ed099e",
"f8e1c9d7-ae45-4433-a315-726c1d912d09"
]
}
Can somebody help me on this please?
EDIT:
What i have is this:
JSONArray obj = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("listId", folderId);
obj.put(jsonObject);
JSONObject json = new JSONObject();
json.put("id", obj);
But this produces something like:
{
"listId":
[
{"id":"c02bc683-fcd7-47a5-b157-853e26ed099e"},
{"id":"f8e1c9d7-ae45-4433-a315-726c1d912d09"}
]
}
Thanks
You've got your array creation a bit mixed up. What you really want is an object holding an array of string, but what you're doing is creating an array of JSONObject.
Try this instead:
String[] arr = { "c02bc683-fcd7-47a5-b157-853e26ed099e", "f8e1c9d7-ae45-4433-a315-726c1d912d09" };
JSONArray jsonArray = new JSONArray(arr);
JSONObject json = new JSONObject();
json.put("listId", jsonArray);
System.out.println(json); // {"listId":["c02bc683-fcd7-47a5-b157-853e26ed099e","f8e1c9d7-ae45-4433-a315-726c1d912d09"]}

Categories