Jackson 의 Object Mapper 클래스 를 기반 으로 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>(){});

총결산
한 줄 안에서 해결 할 수 있 는 문 제 는 일반적으로 상대 적 으로 간단 하 다.

좋은 웹페이지 즐겨찾기