Java 将对象转为 Map 的几种方法

  在 Java 开发中,有时需要将对象转为 Map,以下是几种方式。

一、Java 对象示例。

package com.test.controller;

import lombok.Data;

@Data
public class Student {

    private String name;

    private String sex;
}

二、对象转为 Map 的几种方式

2.1 使用 Jackson

  可以先将对象序列化为 JSON 字符串,然后再将该字符串反序列化为 Map 对象。

package com.test.controller;

import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.util.Map;

public class Test {
    public static void main(String[] args) {

        try {
            Student student = new Student();
            student.setName("张三");

            ObjectMapper mapper = new ObjectMapper();
            String jsonString = mapper.writeValueAsString(student);
            Map<String, Object> tmpMap = mapper.readValue(jsonString, Map.class);
            System.out.println(tmpMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  运行结果如下。

{name=张三, sex=null}

2.2 使用 Gson

package com.test.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.Map;

public class Test {
    public static void main(String[] args) {
        Student student = new Student();
        student.setName("张三");

        Gson gson = new Gson();
        Type targetType = new TypeToken<Map<String, String>>() {
        }.getType();
        Map<String, String> tmpMap = gson.fromJson(gson.toJson(student), targetType);

        System.out.println(tmpMap);
    }
}

  运行结果如下。

{name=张三}

2.3 使用 Guava

  Guava 不直接支持对象到 Map 的转换,需要手动创建 Map 并填充数据。

package com.test.controller;

import com.google.common.collect.Maps;

import java.lang.reflect.Field;
import java.util.Map;

public class Test {
    public static void main(String[] args) {

        try {
            Student student = new Student();
            student.setName("张三");

            Map<String, Object> tmpMap = Maps.newHashMap();
            for (Field field : student.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                tmpMap.put(field.getName(), field.get(student));
            }

            System.out.println(tmpMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

  运行结果如下。

{sex=null, name=张三}

2.4 使用 Hutool

  Hutool 有一个 BeanUtil 类可以直接将对象转换为 Map。

package com.test.controller;

import cn.hutool.core.bean.BeanUtil;

import java.util.Map;

public class Test {
    public static void main(String[] args) {

        Student student = new Student();
        student.setName("张三");

        Map<String, Object> tmpMap = BeanUtil.beanToMap(student);

        System.out.println(tmpMap);
    }
}

  运行结果如下。

{name=张三, sex=null}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值