Create a JSON object using Java

advertisements

I am new to JSON creations . I want to create a JSON object for each element in the for-each loop. My code is like

for(int i=0 ; i<=childclasses.size() ;i++ ){

                for (OInstance oinstance:oinstances){

                    oinstancelist.add(oinstance);

                 }

                }

            try {

                object.put("subclass",oclass);
                object.put("instance", oinstancelist);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("json is  " +object);

I want to create a json object for every oinstance . So,How can i do that ?


With Gson, creating a JSON-String is as easy as:

Gson gson = new Gson();
String json = gson.toJson(oinstance);