ObjectMapper的常用方法 (对象和JSON数据之间的转换)

  
    com.fasterxml.jackson.core  
    jackson-databind  
    2.13.0   

ObjectMapper类是Jackson库中的主要类,用于在Java对象和JSON数据之间进行转换。以下是ObjectMapper的一些常用使用方法:

1. 将JSON字符串转换为Java对象:
String jsonString = "{\"name\":\"John\", \"age\":30}";  
ObjectMapper mapper = new ObjectMapper();  
MyClass obj = mapper.readValue(jsonString, MyClass.class);

2. 将Java对象转换为JSON字符串:
MyClass obj = new MyClass("John", 30);  
ObjectMapper mapper = new ObjectMapper();  
String jsonString = mapper.writeValueAsString(obj);

3. 将JSON数组转换为Java对象数组:
String jsonArrayString = "[{\"name\":\"John\", \"age\":30}, {\"name\":\"Jane\", \"age\":25}]";  
ObjectMapper mapper = new ObjectMapper();  
MyClass[] objArray = mapper.readValue(jsonArrayString, MyClass[].class);

4. 将Java对象数组转换为JSON数组:
MyClass[] objArray = new MyClass[]{new MyClass("John", 30), new MyClass("Jane", 25)};  
ObjectMapper mapper = new ObjectMapper();  
String jsonArrayString = mapper.writeValueAsString(objArray);

5. 将Java集合转换为JSON字符串:
List objList = new ArrayList<>(Arrays.asList(new MyClass("John", 30), new MyClass("Jane", 25)));  
ObjectMapper mapper = new ObjectMapper();  
String jsonArrayString = mapper.writeValueAsString(objList);

6. 将JSON字符串转换为Java Map:
String jsonMapString = "{\"name\":\"John\", \"age\":30}";  
ObjectMapper mapper = new ObjectMapper();  
Map map = mapper.readValue(jsonMapString, new TypeReference>(){});

你可能感兴趣的:(json,java)