JSONObject转换为String一般有两种方法,一种是使用toString()方法,另一种是使用JSONObject.write()方法。
1. 使用toString()方法:
使用toString()方法可以将JSONObject转换为String,其实义就是将JSONObject转换为一个字符串形式的JSON格式。使用该方法非常简单,只需要将JSONObject作为参数传入即可完成转换,如下代码所示:
JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "John"); jsonObject.put("age", 20); String jsonString = jsonObject.toString();
2. 使用JSONObject.write()方法:
使用JSONObject.write()方法可以将JSONObject转换为String,其实义就是将JSONObject转换为一个字符串形式的JSON格式。使用该方法也非常简单,只需要将JSONObject作为参数传入即可完成转换,如下代码所示:
JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "John"); jsonObject.put("age", 20); StringWriter writer = new StringWriter(); jsonObject.write(writer); String jsonString = writer.toString();
以上就是将JSONObject转换为String的常用技巧,使用toString()方法和JSONObject.write()方法可以轻松实现JSONObject到String的转换,但是要注意的是,这两种方法所得到的结果是一样的,只是使用方法不同而已。