1

This is very simple one but struggeling. help me out of this.

I am having a json data { "abc":"test","bed":"cot","help":"me"}

I want to convert above jsonObject into JSON ARRAY like [{ "abc":"test","bed":"cot","help":"me"}]

JSONObject obj= new JSONObject(str.toString());
Iterator x = obj.keys();
JSONArray jsonArray = new JSONArray();
Map<String, String> map = new HashMap<String, String>();
while (x.hasNext()) {
 for(int i=0;i<obj.length();i++) {
 LOG.info("=============");
 String key = (String) x.next();
 jsonArray.put(obj.get(key));
 }
}

I am getting only values. Please help me solve this.

PEHLAJ
10.2k10 gold badges43 silver badges57 bronze badges
asked May 18, 2017 at 11:23
2
  • 1
    Possible duplicate of Add JSONObject to JSONArray java Commented May 18, 2017 at 11:37
  • 1
    Nope ... it's totally different Commented May 18, 2017 at 13:28

2 Answers 2

8

Directly put JsonObject i.e. obj into jsonArray

jsonArray.put(obj);
//result is [{ "abc":"test","bed":"cot","help":"me"}]

Final code

JSONObject obj= new JSONObject(str);
JSONArray jsonArray = new JSONArray();
//simply put obj into jsonArray
jsonArray.put(obj);
//result is [{ "abc":"test","bed":"cot","help":"me"}]
answered May 18, 2017 at 11:41
Sign up to request clarification or add additional context in comments.

2 Comments

may i knw the jar name?
0

It works for me.

JSONObject obj = new JSONObject(result.toString());
JSONArray arr = obj.getJSONArray("value");
paul
4,56919 gold badges83 silver badges156 bronze badges
answered May 18, 2017 at 11:33

2 Comments

Ummm ... use a loop?
Passing string in JSONObject(string) but still getting error . Provided type Map while required type is String.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.