我们如何在Java中将地图转换为JSON对象?
我们可以使用 toJSONString() 方法将 Map 转换为 JSON 对象( >static) 的 org.json.simple.JSONValue。 它有两个重要的静态方法:writeJSONString()方法将对象编码为JSON文本并将其写出,escape()方法转义特殊字符和转义引号,、/、r、n、b、f、t。
示例
import java.util.*; import org.json.simple.JSONValue; public class ConvertMapJSONTest { public static void main(String[] args) { Map 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); // converts Map to JSON System.out.println(jsonStr); } }登录后复制