import org.json.JSONArray;
import org.json.JSONObject;
public class JsonUtils {
public static void main(String[] args) {
// 创建JSONObject对象
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John");
jsonObject.put("age", 25);
jsonObject.put("city", "New York");
// 创建JSONArray对象
JSONArray jsonArray = new JSONArray();
jsonArray.put("apple");
jsonArray.put("banana");
jsonArray.put("orange");
// 将JSONArray添加到JSONObject中
jsonObject.put("fruits", jsonArray);
// 生成JSON字符串
String jsonString = jsonObject.toString();
System.out.println(jsonString);
}
}
输出结果:
{
"name": "John",
"age": 25,
"city": "New York",
"fruits": [
"apple",
"banana",
"orange"
]
}
import com.google.gson.Gson;
public class JsonUtils {
public static void main(String[] args) {
// 创建实体类对象
Person person = new Person("John", 25, "New York");
// 创建Gson对象
Gson gson = new Gson();
// 生成JSON字符串
String jsonString = gson.toJson(person);
System.out.println(jsonString);
}
static class Person {
private String name;
private int age;
private String city;
public Person(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
}
}
输出结果:
{"name":"John","age":25,"city":"New York"}
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtils {
public static void main(String[] args) {
// 创建实体类对象
Person person = new Person("John", 25, "New York");
// 创建ObjectMapper对象
ObjectMapper objectMapper = new ObjectMapper();
try {
// 生成JSON字符串
String jsonString = objectMapper.writeValueAsString(person);
System.out.println(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
static class Person {
private String name;
private int age;
private String city;
public Person(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
}
}
输出结果:
{"name":"John","age":25,"city":"New York"}
这三种方式都可以用于生成JSON字符串,选择使用哪种方式取决于具体的需求和项目中使用的库。