How to convert a JsonObject to a Map in Java?
To convert a JSONObject to a Map, you can do so by using the following method:
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Main {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject("{\"name\":\"John\", \"age\":30}");
Map<String, Object> map = jsonToMap(jsonObject);
System.out.println(map);
}
private static Map<String, Object> jsonToMap(JSONObject jsonObject) {
Map<String, Object> map = new HashMap<>();
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
value = jsonToMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
}
In the code above, we first create a JSONObject object, then call the jsonToMap method to convert it to a Map. The jsonToMap method recursively converts the JSONObject to a Map, and if the value in the JSONObject is also a JSONObject, the jsonToMap method is called recursively. Finally, the converted Map is printed out.
The output is: {name=John, age=30}