在Java中,可以使用以下幾種方式返回JSON數(shù)據(jù):
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);
}
}
輸出結(jié)果為: {"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對象轉(zhuǎn)換為JSON字符串
Person person = new Person("John", 30);
String jsonStr = objectMapper.writeValueAsString(person);
System.out.println(jsonStr);
// 將JSON字符串轉(zhuǎn)換為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;
// 將默認(rèn)的構(gòu)造函數(shù)設(shè)置為public,以便Jackson庫可以使用反射來創(chuàng)建對象
public Person() {}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getter和setter方法省略
}
輸出結(jié)果為:
{"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對象轉(zhuǎn)換為JSON字符串
Person person = new Person("John", 30);
String jsonStr = gson.toJson(person);
System.out.println(jsonStr);
// 將JSON字符串轉(zhuǎn)換為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方法省略
}
輸出結(jié)果與上述使用Jackson庫的例子相同。