Jackson和JSON是什么?
Jackson是Java的一種高效的JSON庫,它可以將Java對象轉換為JSON格式,并將JSON格式轉換為Java對象。JSON(JavaScript Object Notation)是一種既簡單又易于閱讀的輕量級數據交換格式。
Jackson的功能:
import com.fasterxml.jackson.databind.*; //將JSON格式轉換為Java對象 ObjectMapper mapper = new ObjectMapper(); MyClass myObject = mapper.readValue(jsonString, MyClass.class); //將Java對象轉換為JSON格式 ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(myObject);
JSON和Java的映射:
{ "name":"John", "age":30, "cars": [ { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] }, { "name":"BMW", "models":[ "320", "X3", "X5" ] }, { "name":"Fiat", "models":[ "500", "Panda" ] } ] }
可以使用如下Java類映射JSON:
public class Person { private String name; private int age; private Listcars; // getters and setters } public class Car { private String name; private List models; // getters and setters }
Jackson和JSON庫的用法,讓Java對象和JSON格式之間的轉換變得容易。在使用Jackson時,請確保您的項目中包含了jackson.jar和json.jar。