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.

2

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"}]
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");

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.