利用java将json对转为json字符串
时间: 2024-03-17 19:46:28 浏览: 61
可以使用Java中的Gson库来将JSON对象转换成JSON字符串,示例如下:
```java
import com.google.gson.Gson;
public class JsonExample {
public static void main(String[] args) {
// 创建JSON对象
Person person = new Person("John", "Doe", 30);
// 创建Gson对象
Gson gson = new Gson();
// 将JSON对象转换成JSON字符串
String jsonString = gson.toJson(person);
// 输出JSON字符串
System.out.println(jsonString);
}
}
class Person {
private String firstName;
private String lastName;
private int age;
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
```
输出结果为:
```
{"firstName":"John","lastName":"Doe","age":30}
```
阅读全文