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字符串,選擇使用哪種方式取決于具體的需求和項目中使用的庫。