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>(){});
총결산
한 줄 안에서 해결 할 수 있 는 문 제 는 일반적으로 상대 적 으로 간단 하 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
자바 읽 기 쓰기 바 이 너 리 파일 작업텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.