2017-08-17 1 views
-1

In android Ich möchte diese Struktur jsonArray machen:Mehrere Werte von JsonObject ohne Schlüssel in JsonArray

[ 
    {duration: 1, price: 100}, 
    {duration: 2, price: 200}, 
    {duration: 3, price: 300}, 
    {duration: 4, price: 400} 
] 

ich diesen Code geschrieben, aber es ist nicht richtig. Wie kann ich das beheben, damit ich die Ausgabe wie oben erhalten kann?

JSONArray jsonArray = new JSONArray(); 
JSONObject json = new JSONObject(); 
JSONObject oneMonth = new JSONObject(); 

try { 
    oneMonth.put("duration", "1"); 
    oneMonth.put("price", "2"); 
    json.put("oneMonth", oneMonth); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

JSONObject threeMonth = new JSONObject(); 
try { 
    threeMonth.put("duration", "1"); 
    threeMonth.put("price", "2"); 
    json.put("threeMonth", threeMonth); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

JSONObject sixMonth = new JSONObject(); 
try { 
    sixMonth.put("duration", "1"); 
    sixMonth.put("price", "2"); 
    json.put("sixMonth", sixMonth); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

JSONObject twelveMonth = new JSONObject(); 
try { 
    twelveMonth.put("duration", "1"); 
    twelveMonth.put("price", "2"); 
    json.put("twelveMonth", twelveMonth); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

try { 
    jsonArray.put(/*PUT OBJECTS HERE*/); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
+0

was ist, wenn Sie tun, geschieht "jsonArray.put (1 Monat);" – Amit

Antwort

-1

Versuchen Zugabe auf diese Weise:

JSONArray jsonArray = new JSONArray(); 

JSONObject oneMonth = new JSONObject(); 

try { 
    oneMonth.put("duration", "1"); 
    oneMonth.put("price", "100"); 

} catch (JSONException e) { 
    e.printStackTrace(); 
} 

JSONObject threeMonth = new JSONObject(); 
try { 
    threeMonth.put("duration", "2"); 
    threeMonth.put("price", "200"); 

} catch (JSONException e) { 
    e.printStackTrace(); 
} 

JSONObject sixMonth = new JSONObject(); 
try { 
    sixMonth.put("duration", "3"); 
    sixMonth.put("price", "300"); 

} catch (JSONException e) { 
    e.printStackTrace(); 
} 

JSONObject twelveMonth = new JSONObject(); 
try { 
    twelveMonth.put("duration", "4"); 
    twelveMonth.put("price", "400"); 
     } catch (JSONException e) { 
    e.printStackTrace(); 
} 

try { 
    jsonArray.put(oneMonth); 
    jsonArray.put(threeMonth); 
    jsonArray.put(sixMonth); 
    jsonArray.put(twelveMonth); 
} catch (JSONException e) { 
    e.printStackTrace(); 
}