2016-04-29 22 views
0

Ich bin neu in JSON creations. Ich möchte ein JSON-Objekt für jedes Element in der for-each-Schleife erstellen. Mein Code ist wieErstellen Sie ein JSON-Objekt mit Java

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

Ich möchte ein Json-Objekt für jede Instanz erstellen. Also, wie kann ich das tun?

Antwort

0

Mit Gson, einen JSON-String schaffen, ist so einfach wie:

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

Gson gut ist und immer schneller als JSON.

jedoch für JSON, json-simple-1.1.1.jar Holen und in Ihren Classpath hinzufügen und unter Logik schreiben JSON-Objekt

import org.json.simple.JSONObject; 
class JsonEncodeDemo { 
     public static void main(String[] args){ 
     JSONObject obj = new JSONObject(); 
     obj.put("name", "jsonObject"); 
     obj.put("num", new Integer(100)); 
     obj.put("balance", new Double(1000.21)); 
     obj.put("is_vip", new Boolean(true)); 
     System.out.print(obj); 
    } 
} 


Sie eine Ausgabe wie bekommen zu erstellen: { "balance" : 1000.21, "num": 100, "is_vip": true, "name": "jsonObject"}

Wie Sie jedoch neu in JSON sind, können Sie auch this besuchen.