JSON을 내가 만든 Java Bean으로 역 직렬화 / 직렬화하려고합니다. 잭슨과이 노력이 정말 처음 이니 참아주세요. 다음이 있습니다.
{
"foo": {
"firstBlock": {
"myValue": 1,
"someBool": true,
"stringValue": "OK"
},
"anotherBlock": {
"values": [
{
"yikes01": 42
},
{
"yikes02": 215
}
],
"myInt": 64,
"logging": "Yes"
}
}
}
내 Java bean은 JSON의 객체가 반복적으로 사용됨에 따라 여러 개로 나뉩니다.
@JsonRootName("foo")
public class FooBean {
private FirstBlockBean firstBlock;
private AnotherBlockBean anotherBlock;
@JsonGetter("firstBlock")
public FirstBlockBean getFirstBlock() { return firstBlock; }
@JsonSetter("firstBlock")
public void setFirstBlock(FirstBlockBean firstBlock) { this.firstBlock = firstBlock; }
@JsonGetter("anotherBlock")
public AnotherBlockBean getAnotherBlock() { return anotherBlock; }
@JsonSetter("firstBlock")
public void setAnotherBlock(AnotherBlockBean anotherBlock) { this.anotherBlock = anotherBlock; }
}
@JsonRootName("firstBlock")
public class FirstBlockBean {
private int myValue;
private Boolean someBool;
private String stringValue;
@JsonGetter("myValue")
public int getMyValue() { return myValue; }
@JsonSetter("myValue")
public void setMyValue(int myValue) { this.myValue = myValue; }
@JsonGetter("someBool")
public Boolean getSomeBool() { return someBool; }
@JsonSetter("someBool")
public void setSomeBool(Boolean someBool) { this.someBool = someBool; }
@JsonGetter("stringValue")
public String getStringValue() { return stringValue; }
@JsonSetter("someBool")
public void setStringValue(String stringValue) { this.stringValue = stringValue; }
}
... 그리고 AnotherBlockBean
비슷한 방식으로 구현 된 클래스 (간결성을 위해 생략했습니다.) 저는 이것을 위해 Jackson을 사용하고 있습니다. 제 질문은-이 경우에 대해 Jackson에 직렬화 및 역 직렬화를위한 메커니즘이 있습니까? 이상적으로 나는 (여기에서 Google 검색이나 검색을 통해 아무것도 표시 할 수 없었기 때문에 아래의 의사 코드) 줄을 따라 뭔가를 원합니다.
// Assume "node" contains a JsonNode for the tree and foo is an uninitialized FooBean class object.
JsonHelper.deserialize(node, FooBean.class, foo);
이 시점에서 값을 다시 읽을 수 있습니다.
int i = foo.getFirstBlock().getMyValue();
System.out.println("i = " + i); // i = 1
마찬가지로 foo 인스턴스를 가져 와서 다른 메서드를 사용하여 JSON으로 다시 직렬화 할 수 있기를 원합니다. 이런 종류의 내장 기능을 원하거나 존재합니까?
Jackson과 함께 작업 할 때의 주요 클래스는 ObjectMapper입니다. 많은 옵션이 있으며 사용 가능한 방법을 살펴보십시오.
이것은 ObjectMapper를 사용하여 Java 객체와 문자열간에 변환하는 일반적인 도우미 클래스의 예입니다.
public class JsonHelper {
private ObjectMapper objectMapper;
public JsonHelper(){
this.objectMapper = new ObjectMapper();
// Your mapping preferences here
this.objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);
this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
this.objectMapper.setSerializationInclusion(Include.NON_NULL);
this.objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
}
public String serialize(Object object) {
try {
return this.objectMapper.writeValueAsString(object);
} catch (Exception e) {
// TODO Handle exception
return null;
}
}
public <T> T deserialize(String json, Class<T> clazz) {
try {
return this.objectMapper.readValue(json, clazz);
} catch (Exception e) {
// TODO Handle exception
return null;
}
}
public <T> T deserialize(String json, TypeReference<T> valueTypeRef) {
try {
return this.objectMapper.readValue(json, valueTypeRef);
} catch (Exception e) {
// TODO Handle exception
return null;
}
}
}
몇 가지 팁 :
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다