基于Jackson的ObjectMapper类进行json字符串与对象之间的互相转换

版权声明:本文章是作者辛勤书写的成果,如需转载,请与作者联系,并保留作者信息以及原文链接,谢谢~~ https://blog.csdn.net/blueheart20/article/details/81939561

问题

jackson是Java开源领域声名赫赫的json字符串操作类库,与fastjson等齐名。本文将给出示例,如何来快速进行json string和对象之间的互相转换。

代码示例

Profile数据对象类:

@Data
public class Profile {
    private String id;

    //Flag active profile on default
    private boolean activeByDefault;

    //all the user defined properties
    private Map<String, String> properties = new HashMap<>();
}

测试代码:

@Log4j2
public class JsonUtilTest {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void test() throws IOException {
        List<Profile> profiles = new ArrayList<Profile>();

        Profile profile = new Profile();
        profile.setId("dev");
        profile.setActiveByDefault(true);
        Map<String, String> props = new HashMap<>();
        props.put("key.val1", "testval1");
        props.put("key.val2", "testval2");
        profile.setProperties(props);
        profiles.add(profile);

        Profile profile1 = new Profile();
        profile1.setId("test");
        profile1.setActiveByDefault(false);
        Map<String, String> props1 = new HashMap<>();
        props1.put("key.val3", "testval3");
        props1.put("key.val4", "testval4");
        profile1.setProperties(props1);
        profiles.add(profile1);

        String jsonStr = objectMapper.writeValueAsString(profiles);
        log.debug("Json String:" + jsonStr);
        List<Profile> newProfiles = objectMapper.readValue(jsonStr, TypeFactory.defaultInstance().constructCollectionType(List.class, Profile.class));

        log.debug("profiles:" + Arrays.toString(newProfiles.toArray()));
    }
}

测试结果的输出:

10:28:26.323 [main] DEBUG com.jd.ai.code.robot.metadata.JsonUtilTest - Json String:[{"id":"dev","activeByDefault":true,"properties":{"key.val1":"testval1","key.val2":"testval2"}},{"id":"test","activeByDefault":false,"properties":{"key.val3":"testval3","key.val4":"testval4"}}]
10:28:26.359 [main] DEBUG com.jd.ai.code.robot.metadata.JsonUtilTest - profiles:[Profile(id=dev, activeByDefault=true, properties={key.val1=testval1, key.val2=testval2}), Profile(id=test, activeByDefault=false, properties={key.val3=testval3, key.val4=testval4})]

另外一种实现方式:

List<Profile> newProfiles = objectMapper.readValue(jsonStr, new TypeReference<List<Profile>>(){});

总结

能够在一行之内能够解决的问题,一般都是相对比较简单的……

猜你喜欢

转载自blog.csdn.net/blueheart20/article/details/81939561