Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically created JSON Object in Java

Tags:

java

json

I'm trying to build a JSON object in my servlet. The object should look like this:

{
    "firms": [
    {
        "name": "firm1",
        "projects": [
        {
            "name": "firm1project1"
        },
        {
            "name": "firm1project2"
        },
        {
            "name": "firm1project3"
        }
        ]
    },
    {
        "name": "firm2",
        "projects": [
        {
            "name": "firm2project1"
        },
        {
            "name": "firm2project2"
        },
        {
            "name": "firm2project3"
        }
        ]
    },
    {
        "name": "firm3",
        "projects": [
        {
            "name": "firm3project1"
        },
        {
            "name": "firm3project2"
        },
        {
            "name": "firm3project3"
        }
        ]
    },
    {
        "name": "firm4",
        "projects": [
        {
            "name": "firm4project1"
        },
        {
            "name": "firm4project2"
        },
        {
            "name": "firm4project3"
        }
        ]
    }
    ]
}

I have a problem in creating array of project names objects:

[
     {
         "name": "firm2project1"
     },
     {
         "name": "firm2project2"
     },
     {
         "name": "firm2project3"
     }
]

Right now I have the code as showed below (oJsonInner is a JSONObject object, aProjects - ArrayList of JSONObject type). I build the oJsonInner object from the results I get from database query:

while(result.next()){
oJsonInner.put("name",result.getString("project_name"));
aProjects.add(oJsonInner);
}

Is there any way to get the value of the oJsonInner object in aProjects.add(oJsonInner); so during the next loop I could create a new oJsonInner object with different "project_name" value without updating the object that got into aProjects array during the first loop?

like image 444
keshet Avatar asked Aug 31 '26 07:08

keshet


1 Answers

while(result.next()){
   oJsonInner = new JsonObject();
   oJsonInner.put("name",result.getString("project_name"));
   aProjects.add(oJsonInner);
}
like image 185
GreyBeardedGeek Avatar answered Sep 03 '26 04:09

GreyBeardedGeek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!