json 将Map〈String,String>转换为POJO

06odsfpq  于 2022-12-20  发布在  其他
关注(0)|答案(9)|浏览(454)

我一直在研究Jackson,但似乎我必须将Map转换为JSON,然后将生成的JSON转换为POJO。
有没有办法将Map直接转换为POJO?

vatpfxk5

vatpfxk51#

好吧,你也可以用Jackson来实现这一点。(而且自从你考虑用Jackson以来,这似乎更舒服)。
使用ObjectMapperconvertValue方法:

final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);

不需要转换成JSON字符串或其他东西;直接转换要快得多。

2fjabf4q

2fjabf4q2#

采用Gson的解决方案:

Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(map);
MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class);
6tdlim6h

6tdlim6h3#

如果类中有泛型类型,则应将TypeReferenceconvertValue()一起使用。

final ObjectMapper mapper = new ObjectMapper();
final MyPojo<MyGenericType> pojo = mapper.convertValue(map, new TypeReference<MyPojo<MyGenericType>>() {});

你也可以用它把pojo转换成java.util.Map

final ObjectMapper mapper = new ObjectMapper();
final Map<String, Object> map = mapper.convertValue(pojo, new TypeReference<Map<String, Object>>() {});
3duebb1j

3duebb1j4#

ObjectMapper objectMapper = new ObjectMapper();
// Use this if all properties are not in the class
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final MyPojo pojo = objectMapper.convertValue(map, MyPojo.class);

和第一个答案一样,但是我得到了一个错误,因为我不想把Map的所有属性都转换成这个类,我还找到了objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);作为解决方案。

b09cbbtk

b09cbbtk5#

是的,完全可以避免中间的JSON转换。使用像Dozer这样的深度复制工具,您可以直接将Map转换为POJO。下面是一个简单的示例:
POJO示例:

public class MyPojo implements Serializable {
    private static final long serialVersionUID = 1L;

    private String id;
    private String name;
    private Integer age;
    private Double savings;

    public MyPojo() {
        super();
    }

    // Getters/setters

    @Override
    public String toString() {
        return String.format(
                "MyPojo[id = %s, name = %s, age = %s, savings = %s]", getId(),
                getName(), getAge(), getSavings());
    }
}

转换代码示例:

public class CopyTest {
    @Test
    public void testCopyMapToPOJO() throws Exception {
        final Map<String, String> map = new HashMap<String, String>(4);
        map.put("id", "5");
        map.put("name", "Bob");
        map.put("age", "23");
        map.put("savings", "2500.39");
        map.put("extra", "foo");

        final DozerBeanMapper mapper = new DozerBeanMapper();
        final MyPojo pojo = mapper.map(map, MyPojo.class);
        System.out.println(pojo);
    }
}

输出:
[ID = 5,姓名=鲍勃,年龄= 23,储蓄= 2500.39]
注意:如果你将源Map更改为Map<String, Object>,那么你可以复制任意深度嵌套的属性(使用Map<String, String>你只能得到一层)。

qaxu7uf2

qaxu7uf26#

我已经测试了Jackson和BeanUtils,发现BeanUtils要快得多。
在我的机器(Windows8.1,JDK1.7)中,我得到了这个结果。

BeanUtils t2-t1 = 286
Jackson t2-t1 = 2203
public class MainMapToPOJO {

public static final int LOOP_MAX_COUNT = 1000;

public static void main(String[] args) {
    Map<String, Object> map = new HashMap<>();
    map.put("success", true);
    map.put("data", "testString");

    runBeanUtilsPopulate(map);

    runJacksonMapper(map);
}

private static void runBeanUtilsPopulate(Map<String, Object> map) {
    long t1 = System.currentTimeMillis();
    for (int i = 0; i < LOOP_MAX_COUNT; i++) {
        try {
            TestClass bean = new TestClass();
            BeanUtils.populate(bean, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    long t2 = System.currentTimeMillis();
    System.out.println("BeanUtils t2-t1 = " + String.valueOf(t2 - t1));
}

private static void runJacksonMapper(Map<String, Object> map) {
    long t1 = System.currentTimeMillis();
    for (int i = 0; i < LOOP_MAX_COUNT; i++) {
        ObjectMapper mapper = new ObjectMapper();
        TestClass testClass = mapper.convertValue(map, TestClass.class);
    }
    long t2 = System.currentTimeMillis();
    System.out.println("Jackson t2-t1 = " + String.valueOf(t2 - t1));
}}
lx0bsm1f

lx0bsm1f7#

到目前为止,使用Jackson提供的答案非常好,但您仍然可以使用一个 util 函数来帮助您 * 转换 * 不同的POJO,如下所示:

public static <T> T convert(Map<String, Object> aMap, Class<T> t) {
        try {
            return objectMapper
                    .convertValue(aMap, objectMapper.getTypeFactory().constructType(t));
        } catch (Exception e) {
            log.error("converting failed! aMap: {}, class: {}", getJsonString(aMap), t.getClass().getSimpleName(), e);
        }
        return null;
    }
kiayqfof

kiayqfof8#

将Map转换为POJO示例。注意Map键包含下划线,字段变量为驼峰。
用户类POJO

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class User {
    @JsonProperty("user_name")
    private String userName;
    @JsonProperty("pass_word")
    private String passWord;
}

App.class测试该示例

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class App {
    public static void main(String[] args) {
        Map<String, String> info = new HashMap<>();
        info.put("user_name", "Q10Viking");
        info.put("pass_word", "123456");

        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.convertValue(info, User.class);

        System.out.println("-------------------------------");
        System.out.println(user);
    }
}
/**output
-------------------------------
User(userName=Q10Viking, passWord=123456)
 */
xriantvc

xriantvc9#

@Hamedz如果使用许多数据,使用Jackson转换光数据,使用apache...测试用例:

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

public class TestPerf {

    public static final int LOOP_MAX_COUNT = 1000;

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        map.put("number", 1000);
        map.put("longer", 1000L);
        map.put("doubler", 1000D);
        map.put("data1", "testString");
        map.put("data2", "testString");
        map.put("data3", "testString");
        map.put("data4", "testString");
        map.put("data5", "testString");
        map.put("data6", "testString");
        map.put("data7", "testString");
        map.put("data8", "testString");
        map.put("data9", "testString");
        map.put("data10", "testString");

        runBeanUtilsPopulate(map);

        runJacksonMapper(map);
    }

    private static void runBeanUtilsPopulate(Map<String, Object> map) {
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < LOOP_MAX_COUNT; i++) {
            try {
                TestClass bean = new TestClass();
                BeanUtils.populate(bean, map);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        long t2 = System.currentTimeMillis();
        System.out.println("BeanUtils t2-t1 = " + String.valueOf(t2 - t1));
    }

    private static void runJacksonMapper(Map<String, Object> map) {
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < LOOP_MAX_COUNT; i++) {
            ObjectMapper mapper = new ObjectMapper();
            TestClass testClass = mapper.convertValue(map, TestClass.class);
        }
        long t2 = System.currentTimeMillis();
        System.out.println("Jackson t2-t1 = " + String.valueOf(t2 - t1));
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class TestClass {
        private Boolean success;
        private Integer number;
        private Long longer;
        private Double doubler;
        private String data1;
        private String data2;
        private String data3;
        private String data4;
        private String data5;
        private String data6;
        private String data7;
        private String data8;
        private String data9;
        private String data10;

    }
}

相关问题