在Java中,可以使用以下幾種方式返回JSON數據:
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John");
jsonObject.put("age", 30);
String jsonStr = jsonObject.toString();
System.out.println(jsonStr);
}
}
輸出結果為: {"name":"John","age":30}
使用Jackson庫:
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
// 將Java對象轉換為JSON字符串
Person person = new Person("John", 30);
String jsonStr = objectMapper.writeValueAsString(person);
System.out.println(jsonStr);
// 將JSON字符串轉換為Java對象
Person person2 = objectMapper.readValue(jsonStr, Person.class);
System.out.println(person2.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
// 將默認的構造函數設置為public,以便Jackson庫可以使用反射來創建對象
public Person() {}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getter和setter方法省略
}
輸出結果為:
{"name":"John","age":30}
John
使用Gson庫:
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
try {
// 將Java對象轉換為JSON字符串
Person person = new Person("John", 30);
String jsonStr = gson.toJson(person);
System.out.println(jsonStr);
// 將JSON字符串轉換為Java對象
Person person2 = gson.fromJson(jsonStr, Person.class);
System.out.println(person2.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getter和setter方法省略
}
輸出結果與上述使用Jackson庫的例子相同。