Map集合 & 实体类对象的相互转换

一、Map转实体类

1. fastjson工具类

导入依赖


   com.alibaba
    fastjson
    1.2.54

代码实现 

   Map authorMap = new HashMap<>();
        authorMap.put("id", 10L);
        authorMap.put("name", "蜡笔小新");
        authorMap.put("category", "分类");
        authorMap.put("score", 90);
        authorMap.put("intro", "简介");
        Book book = JSON.parseObject(JSON.toJSONString(authorMap), Book.class);
        System.out.println(book);

2. Jackson工具类

导入依赖



    com.fasterxml.jackson.core
    jackson-core
    2.12.5




    com.fasterxml.jackson.core
    jackson-databind
    2.12.5

代码实现

import com.fasterxml.jackson.databind.ObjectMapper;

Map personMap = new HashMap<>();
personMap.put("name", "John");
personMap.put("age", 20);

ObjectMapper mapper = new ObjectMapper();
Person person = mapper.convertValue(personMap, Person.class);

3. apache.commons.beanutils工具类

导入依赖


     commons-beanutils
     commons-beanutils
     1.8.0
     compile

代码实现

Map map = new HashMap<>();
map.put("id", 1);
map.put("name", "John");
map.put("age", 25);
Person person = new Person();
BeanUtils.populate(person, map);

二、实体类转Map

1. fastjson工具类

导入依赖


   com.alibaba
    fastjson
    1.2.54

代码实现

        Book book1 = new Book();
        book1.setId(1l);
        book1.setName("风间");
        book1.setCategory("分类");
        book1.setIntro("简介");
        book1.setScore(100);
        Map map = JSON.parseObject(JSON.toJSONString(book1), Map.class);
        System.out.println(map);

2. Jackson工具类

导入依赖



    com.fasterxml.jackson.core
    jackson-core
    2.12.5




    com.fasterxml.jackson.core
    jackson-databind
    2.12.5

代码实现

import com.fasterxml.jackson.databind.ObjectMapper;

Person person = new Person("John", 20);

ObjectMapper mapper = new ObjectMapper();
Map personMap = mapper.convertValue(person, Map.class);

3. apache.commons.beanutils工具类

导入依赖


     commons-beanutils
     commons-beanutils
     1.8.0
     compile

代码实现

Map map = BeanUtils.describe(person);
map.remove("class");

你可能感兴趣的:(后端,#,java,java)