I have a JSONObject:
try {
JSONObject myJsonObject = new JSONObject("{ \"options\": [\"Oui\", \"Non\"] }");
JSONArray myJsonArray = myJsonObject.getJSONArray("options");
} catch (Exception e) {
e.printStackTrace();
}
myJsonArray.toString() contain:
["Yes", "No"]
I need to convert it to a JSONObject like this:
{ "0": "Yes", "1": "No" }
and also to:
{ "Yes": "Yes", "No": "No" }
Any idea how I can do this?
-
Did you try something?? If not please try to do on your own first. Its not something very difficult. Just about the loop and creation of object for each item of arrayRohit5k2– Rohit5k22014年12月18日 22:13:21 +00:00Commented Dec 18, 2014 at 22:13
-
I'm so stupid, of course : for(int i = 0; i < myJsonArray.length(); i++){ String a = myJsonArray.getString(i); }brunto– brunto2014年12月18日 22:17:37 +00:00Commented Dec 18, 2014 at 22:17
2 Answers 2
Of course the answer is :
JSONObject myJsonObject = new JSONObject("{ \"options\": [\"Oui\", \"Non\"] }");
JSONArray myJsonArray = myJsonObject.getJSONArray("options");
JSONObject myJsonObject2 = new JSONObject();
for(int i = 0; i < myJsonArray.length(); i++){
String a = myJsonArray.getString(i);
myJsonObject2.put(a, a);
}
Sorry, I got confused.
Sign up to request clarification or add additional context in comments.
Comments
There is a method toJSONObject for creating new JSONObjects from a JSONArray. Try this:
try {
JSONObject myJsonObject = new JSONObject("{ \"options\": [\"Oui\", \"Non\"] }");
JSONArray myJsonArray = myJsonObject.getJSONArray("options");
// creates a new JSON Object with the given keys
JSONObject result = myJsonArray.toJSONObject(myJsonArray);
} catch (Exception e) {
e.printStackTrace();
}
answered Aug 10, 2016 at 9:42
Radon8472
5,0672 gold badges39 silver badges50 bronze badges
Comments
lang-java