广告
返回顶部
首页 > 资讯 > 后端开发 > Python >使用Jackson实现Map与Bean互转方式
  • 202
分享到

使用Jackson实现Map与Bean互转方式

2024-04-02 19:04:59 202人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

Jackson Map与Bean互转 在使用 java 开发中,通常需要把 Map 转成 Bean,或把 Bean 转成 Map,这就用的工具类,在此推荐使用import com.f

Jackson Map与Bean互转

在使用 java 开发中,通常需要把 Map 转成 Bean,或把 Bean 转成 Map,这就用的工具类,在此推荐使用import com.fasterxml.jackson.databind.ObjectMapper;包下的ObjectMapper类,比 JSONObject 效率高

下面就列举了几种使用方法

1、pom.xml


<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.6</version>
    <scope>compile</scope>
</dependency>

2、java 代码


package com.jin.demo.jackson;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

public class JacksonTest {
    private static final ObjectMapper mapper = new ObjectMapper();
    public static void main(String[] args) throws Exception {
        // 测试 将Map转成指定的Bean
        Map<String, Object> map = new HashMap<>();
        map.put("name", "张三");
        Person o = (Person)JacksonTest.mapToBean(map, Person.class);
        System.out.println(o);
        // 测试 将Bean转成Map
        Person person = new Person();
        person.setAge(18);
        Map map1 = JacksonTest.beanToMap(person);
        System.out.println(map1);
    }
    // 将对象转成字符串
    public static String objectToString(Object obj) throws Exception {
        return mapper.writeValueAsString(obj);
    }
    // 将Map转成指定的Bean
    public static Object mapToBean(Map map, Class clazz) throws Exception {
        return mapper.readValue(objectToString(map), clazz);
    }
    // 将Bean转成Map
    public static Map beanToMap(Object obj) throws Exception {
        return mapper.readValue(objectToString(obj), Map.class);
    }
}

3、Person 类


package com.jin.demo.jackson;
import java.io.Serializable;
import java.util.Date;

public class Person implements Serializable {
    private int age;
    private String name;
    private Date birthday;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

Jackson-ObjectMapper json字符串、bean、map、list互相转换

1、对象转json字符串


ObjectMapper mapper = new ObjectMapper();
User user = new User();
String userJson = mapper.writeValueAsString(user);

2、Map转json字符串


ObjectMapper mapper = new ObjectMapper();
Map map = new HashMap();
String json = mapper.writeValueAsString(map);

3、数组list转json字符串


ObjectMapper mapper = new ObjectMapper();
User[] uArr = {user1, user2};
String jsonfromArr = mapper.writeValueAsString(uArr);

4、json字符串转对象


ObjectMapper mapper = new ObjectMapper();
String expected = "{\"name\":\"ZhangSan\"}";
User user = mapper.readValue(expected, User.class);

5、json字符串转Map


ObjectMapper mapper = new ObjectMapper();
String expected = "{\"name\":\"ZhangSan\"}";
Map userMap = mapper.readValue(expected, Map.class);

6、json字符串转对象数组List


ObjectMapper mapper = new ObjectMapper();
String expected = "[{\"name\":\"Zhangsan\"},{\"name\":\"Lisi\"}]";
CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, User.class);
List<User> userList = mapper.readValue(expected, listType);

7、json字符串转Map数组List<Map<String,Object>>


ObjectMapper mapper = new ObjectMapper();
String expected = "[{\"name\":\"Zhangsan\"},{\"nameEn\":\"Lisi\"}]";
CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Map.class);
List<Map<String,Object>> userList = mapper.readValue(expected, listType);

8、jackson默认将对象转换为LinkedHashMap


ObjectMapper mapper = new ObjectMapper();
String expected = "[{\"name\":\"Zhangsan\"},{\"nameEn\":\"Lisi\"},{\"name\":\"Test\"}]";
ArrayList arrayList = mapper.readValue(expected, ArrayList.class);

9、json字符串转对象设置格式


ObjectMapper mapper = new ObjectMapper();
//设置date转换格式
SimpleDateFORMat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mapper.setDateFormat(fmt);
String expected = "{\"name\":\"ZhangSan\",\"bir\":\"2021-04-15 14:00:00\"}";
User user = mapper.readValue(expected, User.class);

10、忽略未知字段


ObjectMapper mapper = new ObjectMapper();
//设置忽略未知字段
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String expected = "{\"name\":\"ZhangSan\",\"job\":\"teacher\"}";
User user = mapper.readValue(expected, User.class);

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: 使用Jackson实现Map与Bean互转方式

本文链接: https://www.lsjlt.com/news/132993.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作