本文主要是介绍ObjectMapper的常用方法 (对象和JSON数据之间的转换),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.0</version> <!-- 请根据实际情况选择合适的版本 -->
</dependency>
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<MyClass> 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<String, Object> map = mapper.readValue(jsonMapString, new TypeReference<Map<String, Object>>(){});
这篇关于ObjectMapper的常用方法 (对象和JSON数据之间的转换)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!