How to convert a map to JSON in Android?
In Android, the JSONObject class can be used to convert a Map object into JSON format. Here is an example code snippet:
import org.json.JSONObject;
import java.util.Map;
public class MapToJsonConverter {
public static String mapToJson(Map<String, String> map) {
JSONObject jsonObject = new JSONObject(map);
return jsonObject.toString();
}
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
String json = mapToJson(map);
System.out.println(json);
}
}
Firstly, in the above code, a Map object is created and populated with data. Next, the mapToJson method is called to convert the Map object into a JSONObject object. Finally, the JSONObject object is converted into a JSON formatted string by calling the toString() method, and then printed out.