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
user6250770
6922 gold badges10 silver badges26 bronze badges
-
1Possible duplicate of Add JSONObject to JSONArray javaNico Van Belle– Nico Van Belle2017年05月18日 11:37:48 +00:00Commented May 18, 2017 at 11:37
-
1Nope ... it's totally differentuser6250770– user62507702017年05月18日 13:28:44 +00:00Commented May 18, 2017 at 13:28
2 Answers 2
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
PEHLAJ
10.2k10 gold badges43 silver badges57 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Arunkumar Thangavel
may i knw the jar name?
PEHLAJ
@ArunkumarThangavel These are built-in classes. developer.android.com/reference/org/json/JSONObject developer.android.com/reference/org/json/JSONArray
It works for me.
JSONObject obj = new JSONObject(result.toString());
JSONArray arr = obj.getJSONArray("value");
paul
4,56919 gold badges83 silver badges156 bronze badges
2 Comments
Stephen C
Ummm ... use a loop?
Ajeet Yadawa
Passing string in JSONObject(string) but still getting error . Provided type Map while required type is String.
lang-java