2013-12-13 15 views
5

Sto lavorando su Json Objects in java !. Ho oggetti JSON 2 come segue:Aggiungere 2 oggetti json in base alle chiavi in ​​java

{"a":{"num1":5},"b":{"num1":8}} 

{"a":{"num2":7},"b":{"num2":9}} 

voglio creare un oggetto JSON singolo come:

{"a":{"num1":5,"num2":7},"b":{"num1":8,"num2":9}} 

Come devo unire i 2 oggetti per raggiungere il risultato di cui sopra?

+0

Come viene rappresentato il JSON in Java? Sono stringhe? Stai già utilizzando una libreria? – robbmj

+0

dovresti controllare questo http://stackoverflow.com/questions/2403132/concat-multiple-jsonobjects –

risposta

1

Il modo più semplice è quello di creare la lista e un ciclo su due oggetti:

public static void main(String[] args) { 
    String str1 = "{\"a\":{\"num1\":5},\"b\":{\"num1\":8}}"; 
    String str2 = "{\"a\":{\"num2\":7},\"b\":{\"num2\":9}}"; 

    try { 
     JSONObject str1Json = new JSONObject(str1); 
     JSONObject str2Json = new JSONObject(str2); 

     List<JSONObject> list = Arrays.asList(str1Json, str2Json); 

     JSONObject storage = new JSONObject(); 
     JSONObject storageA = new JSONObject(); 
     JSONObject storageB = new JSONObject(); 
     JSONObject a; 
     JSONObject b; 
     JSONObject obj; 

     for(int i=1; i<= list.size(); i++){ 

      obj = list.get(i-1); 

      a = obj.getJSONObject("a"); 
      b = obj.getJSONObject("b"); 

      storageA.put("num"+i, a.getInt("num"+i)); // we don't want build list    
      storageB.put("num"+i, b.getInt("num"+i));    
     } 

     storage.put("a", storageA); 
     storage.put("b", storageB); 

     System.out.println(storage.toString()); 
    } catch (JSONException e1) { 
    } 
} 

uscita:

{"b":{"num2":9,"num1":8},"a":{"num2":7,"num1":5}} 
0

Convertire il JSON oggetti in dizionari utilizzando [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; e quindi eseguire le manipolazioni con facilità.

Problemi correlati