0

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?

2
  • 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 array Commented 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); } Commented Dec 18, 2014 at 22:17

2 Answers 2

1

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

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.