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

问题

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 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 profiles = new ArrayList();

        Profile profile = new Profile();
        profile.setId("dev");
        profile.setActiveByDefault(true);
        Map 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 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 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 newProfiles = objectMapper.readValue(jsonStr, new TypeReference<List>(){});

总结

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

你可能感兴趣的:(Java技术,服务化与Spring,Cloud,Spring,Boot实战)