import org.json.JSONArray;
import org.json.JSONObject;
public class JsonUtils {
public static void main(String[] args) {
// 創(chuàng)建JSONObject對(duì)象
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John");
jsonObject.put("age", 25);
jsonObject.put("city", "New York");
// 創(chuàng)建JSONArray對(duì)象
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);
}
}
輸出結(jié)果:
{
"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) {
// 創(chuàng)建實(shí)體類對(duì)象
Person person = new Person("John", 25, "New York");
// 創(chuàng)建Gson對(duì)象
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;
}
}
}
輸出結(jié)果:
{"name":"John","age":25,"city":"New York"}
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtils {
public static void main(String[] args) {
// 創(chuàng)建實(shí)體類對(duì)象
Person person = new Person("John", 25, "New York");
// 創(chuàng)建ObjectMapper對(duì)象
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;
}
}
}
輸出結(jié)果:
{"name":"John","age":25,"city":"New York"}
這三種方式都可以用于生成JSON字符串,選擇使用哪種方式取決于具體的需求和項(xiàng)目中使用的庫。