将JSONObject转换为String的最简单方法是使用其toString()方法。例如:
JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", "value1");
jsonObject.put("key2", "value2");
String jsonString = jsonObject.toString();
System.out.println(jsonString);
这将打印出JSON对象的字符串表示形式:
{"key1":"value1","key2":"value2"}
另外,也可以使用Jackson库的ObjectMapper类来实现JSONObject到String的转换。例如:
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(jsonObject);
System.out.println(jsonString);
这种方法在处理更复杂的JSON结构时更加灵活和强大。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:jsonobject的性能优化技巧有哪些