JSONValue.toJSONString(Map)
Lớp tiện ích JSONValue cung cấp phương thức tĩnh toJSONString(Map) chuyển đổi Map trực tiếp thành chuỗi JSON object. Nội bộ nó tạo JSONObject từ Map và gọi toJSONString().
Ví dụ
import java.util.*;
import org.json.simple.JSONValue;
public class MapToJsonExample {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("1", "India");
map.put("2", "Australia");
map.put("3", "England");
map.put("4", "South Africa");
String jsonStr = JSONValue.toJSONString(map);
System.out.println(jsonStr);
}
}
Kết quả
{"1":"India","2":"Australia","3":"England","4":"South Africa"}
Các phương thức hữu ích khác của JSONValue:
writeJSONString(Map, Writer)– ghi JSON trực tiếp ra Writerescape(String)– escape các ký tự đặc biệt JSON (\", \\, /, \r, \n, \b, \f, \t)