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();
Related
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);
}
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();
}
I need to transform my data in a ArrayList to a JSON file, and I use JSON.simple. Everything is fine except one little thing that I want to get a result like ...... {source:0, target:1},{source:0, target:1},{source:0, target:2},{source:0, target:3} ...... but it returns ......{source:0, target:16},{source:0, target:16},{source:0, target:16}...... . My solution.size() is 17.
Here is my code:
JSONObject jsonObject = new JSONObject();
JSONObject jsonNodesObject = new JSONObject();
JSONObject jsonEdgesObject = new JSONObject();
JSONArray jsonNodesArray = new JSONArray();
JSONArray jsonEdgesArray = new JSONArray();
String instString = solutions.get(0).get("institution");
jsonNodesObject.put("name", instString);
// extract name and institution from ArrayList
for (int i = 0; i < solutions.size(); i++)
{
HashMap<String, String> eleHashMap= solutions.get(i);
String nameString = eleHashMap.get("name");
jsonNodesObject.put("name", nameString);
jsonNodesArray.add(jsonNodesObject);
jsonEdgesObject.put("source", 0);
jsonEdgesObject.put("target", i);
jsonEdgesArray.add(jsonEdgesObject);
}
jsonObject.put("nodes", jsonNodesArray);
jsonObject.put("edges", jsonEdgesArray);
System.out.println(jsonObject);
It seems that in every for loop, it refreshes the value of target: i of all my jsonEdgesArray.
Dose anyone know how to fix this? Thanks in advance!
As your iterating jsonNodesObject in for loop, same value will be put for jsonNodesObject.put("name", nameString); u have to initialize JSONObject jsonNodesObject = new JSONObject(); inside for loop
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
I have written java code for generating json of my searched data from file.But its not generating exact JsonArray. Its like
[{"item":"1617"},{"item":"1617"}]
instead of
[{"item":"747"},{"item":"1617"}].
Here 1617 is last item which is fetched from file.
JSONArray ja = new JSONArray();
JSONObject jo = new JSONObject();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID);
if(j == userId) {
itemid = products.get("item");
jo.put("item",itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
you are actually creating one jSONobject object to handle two objects, shouldn't you need to create JSONObjects in the while loop? something like this, so every iteration in while loop will create a new JSONObject and add it to JSONArray
JSONArray ja = new JSONArray();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID, 10);
if(j == userId)
{
JSONObject jo = new JSONObject();
itemid = products.get("item");
jo.put("item", itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
Extra:
i am not sure how java does conversion for string to integer, but i think you should always specify radix when using parseInt so the strings like '09' will not be treated as octal value and converted to wrong value (atleast this is true in javascript :))
Integer.parseInt(productID, 10);
You must re-instantiate your JSonObject inside the loop because when you modify it you modify the underlying object which is referenced several times by your array. Move your JSONObject jo = new JSONObject(); inside the loop and it should work fine.
Place JSONObject jo = new JSONObject(); inside the loop:
while (products.readRecord())
{
JSONObject jo = new JSONObject();
String productID = products.get("user");
int j = Integer.parseInt(productID);
// etc
}