java JSONObject转string
时间: 2023-07-20 19:42:02 浏览: 92
要将Java中的 `JSONObject` 对象转换为字符串,可以使用 `toString()` 方法。以下是一个简单的示例代码:
```java
import org.json.JSONObject;
public class JSONObjectToString {
public static void main(String[] args) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", "John");
jsonObj.put("age", 30);
jsonObj.put("city", "New York");
String jsonString = jsonObj.toString();
System.out.println(jsonString);
}
}
```
在上述代码中,我们首先创建了一个 `JSONObject` 对象 `jsonObj`,并向其中添加了三个属性和值。然后,我们调用 `jsonObj.toString()` 方法将其转换为字符串,并将结果存储在 `jsonString` 变量中。最后,我们使用 `System.out.println()` 方法将其输出到控制台。
执行上述代码后,我们可以看到以下输出结果:
```
{"city":"New York","name":"John","age":30}
```
可以看到,`jsonObj.toString()` 方法将 `JSONObject` 对象转换为了一个包含所有属性和值的字符串。
阅读全文
相关推荐

















