java中Fastjson怎么使用

小億
103
2023-09-21 22:48:32

Fastjson是一款Java中非常流行的JSON處理工具,可以用于JSON的解析和生成。下面是一些使用Fastjson的常見操作:

  1. 將對(duì)象轉(zhuǎn)換為JSON字符串:
Person person = new Person("Tom", 18);
String jsonString = JSON.toJSONString(person);
System.out.println(jsonString);
  1. 將JSON字符串轉(zhuǎn)換為對(duì)象:
String jsonString = "{\"name\":\"Tom\",\"age\":18}";
Person person = JSON.parseObject(jsonString, Person.class);
System.out.println(person.getName());
System.out.println(person.getAge());
  1. 將JSON字符串轉(zhuǎn)換為JSONObject對(duì)象:
String jsonString = "{\"name\":\"Tom\",\"age\":18}";
JSONObject jsonObject = JSON.parseObject(jsonString);
System.out.println(jsonObject.getString("name"));
System.out.println(jsonObject.getInteger("age"));
  1. 將JSON字符串轉(zhuǎn)換為JSONArray對(duì)象:
String jsonString = "[{\"name\":\"Tom\",\"age\":18},{\"name\":\"Jerry\",\"age\":20}]";
JSONArray jsonArray = JSON.parseArray(jsonString);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.getString("name"));
System.out.println(jsonObject.getInteger("age"));
}
  1. 將Map對(duì)象轉(zhuǎn)換為JSON字符串:
Map<String, Object> map = new HashMap<>();
map.put("name", "Tom");
map.put("age", 18);
String jsonString = JSON.toJSONString(map);
System.out.println(jsonString);
  1. 將JSON字符串轉(zhuǎn)換為Map對(duì)象:
String jsonString = "{\"name\":\"Tom\",\"age\":18}";
Map<String, Object> map = JSON.parseObject(jsonString, new TypeReference<Map<String, Object>>() {});
System.out.println(map.get("name"));
System.out.println(map.get("age"));

這些是Fastjson的一些基本使用方法,可以根據(jù)具體的需求進(jìn)行深入學(xué)習(xí)和使用。

0