자바 객체를 JSON 변환할지 데릭쉐퍼드와 특정 문자열을. 나는 잭슨 JSON 위해 사용하는 방식이다. Json 입력입니다 제어할 수 없어요 (I) 를 읽은 웹 서비스). 이건 내 입력입니다 JSON:
{"wrapper":[{"id":"13","name":"Fred"}]}
여기서 는 간편화된 览侩 荤례:
private void tryReading() {
String jsonStr = "{\"wrapper\"\:[{\"id\":\"13\",\"name\":\"Fred\"}]}";
ObjectMapper mapper = new ObjectMapper();
Wrapper wrapper = null;
try {
wrapper = mapper.readValue(jsonStr , Wrapper.class);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("wrapper = " + wrapper);
}
내 엔티티입니다 클래스는:
public Class Student {
private String name;
private String id;
//getters & setters for name & id here
}
내 래퍼 클래스인 컨테이너입니다 객체에는 기본적으로 afaq 내 목록니다 재학생:
public Class Wrapper {
private List<Student> students;
//getters & setters here
}
난 계속 이 가져오는 오류 및 " wrapper"; 'null' 되돌려줍니다. # 39 의 누각되었습니다 what& 실로나는 확실하지 않다. 구해줘 수 있을까요?
org.codehaus.jackson.map.exc.UnrecognizedPropertyException:
Unrecognized field "wrapper" (Class Wrapper), not marked as ignorable
at [Source: java.io.StringReader@1198891; line: 1, column: 13]
(through reference chain: Wrapper["wrapper"])
at org.codehaus.jackson.map.exc.UnrecognizedPropertyException
.from(UnrecognizedPropertyException.java:53)
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
@JsonIgnoreProperties
class { ... }
@JsonIgnoreProperties(ignoreUnknown = true)
첫 번째 대답은 거의 정확하지만 필요한 것은 아닌 getter 메서드 변경하십시오 필드이므로 - 필드는 보면안돼 아닌 자동 감지). 또한 게터 우선합니다 필드용 둘 다 볼 수 있다. (방법이 비공개 필드용 가시적입니다 역시 가질 수 있지만, s 별로 스케쳐내 getter there& # 39 점)
그래서 할 수 있는 '또는' getter 인컨텍스트 제라이퍼 () 라는 주석이.
@JsonProperty("wrapper")
원할 경우 getter 메서드 이름 그대로.
잭슨은 이 협력했습니다 사용하여 2.6.0 가져다줄래요:
private static final ObjectMapper objectMapper =
new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
또한 설정:
@JsonIgnoreProperties(ignoreUnknown = true)
이 2 가지 방법으로 수행할 수 있습니다.
@JsonIgnoreProperties (이흐노룬나운 = true)
로비치 대퍼 매퍼에서 = new 로비치 대퍼 (); 마이클 잭슨의 아동 성희롱 버전 1.X // 마페리콘피구레 (DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false). 마이클 잭슨의 아동 성희롱 버전 2.X // 마페리콘피구레 (DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
이 작품은 이 재산이잖아 것보단 참조하십시오.
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
projectVO = objectMapper.readValue(yourjsonstring, Test.class);
Doc 에 따르면 선택한 필드용 또는 모든 우나운 필드용 무시할 수 있습니다.
// to prevent specified fields from being serialized or deserialized
// (i.e. not include in JSON output; or being set even if they were included)
@JsonIgnoreProperties({ "internalId", "secretKey" })
// To ignore any unknown properties in JSON input without exception:
@JsonIgnoreProperties(ignoreUnknown=true)
나도 날잡아 아래 방법 및 작동하잖아 이러한 JSON format 판독값 잭슨이에요 함께 이미 제안됩니다 솔루션을 사용할 수 있습니다. 달기 '킬러' 로 @JsonProperty (wrapper" ";)
네 래퍼 클래스
public Class Wrapper{
private List<Student> students;
//getters & setters here
}
내 제안에 래퍼 (wrapper) 의 클래스
public Class Wrapper{
private StudentHelper students;
//getters & setters here
// Annotate getter
@JsonProperty("wrapper")
StudentHelper getStudents() {
return students;
}
}
public class StudentHelper {
@JsonProperty("Student")
public List<Student> students;
//CTOR, getters and setters
//NOTE: If students is private annotate getter with the annotation @JsonProperty("Student")
}
그러나 이는 제공하십시오 출력물에는 형식:
{"wrapper":{"student":[{"id":13,"name":Fred}]}}
또한 자세한 내용은 https://github.com/FasterXML/jackson-annotations
이렇게 하면 된다.
이 솔루션은 스트리밍합니다 중 일부만 가져올 필요가 없는 동안 읽을 때 일반 json 필드용 필드용 제대로 매핑되었습니다 도메인에 클래스뿐만 무시할 수 있습니다.
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
세부적인 솔루션 될 것이라고 같은 도구를 사용하여 jsonschema2pojo 오토제너레이터 에서 json 의 위해 필요한 도메인 클래스뿐만 스키마에는 수강생용 같은 반응을 보였다. 모든 온라인 json 스키마에는 변환기) 를 통해 rmw 수행할 수 있습니다.
[https://firebase.google.com/support/guides/firebase-android] :
Sdk 2.x 와 db 는 자바 객체를 자동으로 변환, 중포 기지 () '에' 로 읽을 수 있게 하는 자바 객체를 JSON 및 JSON 다타바저페렌시오스트발루 패스를 통해 '데이타스나프쇼t.제발루 ()'.
자바 객체를 JSON 읽을 때, 새로운 SDK 를 함께 데이타스나프쇼t.제발루 () ',' 이제 더 이상 필요 없는 '에서 알 수 없는 속성 때문에 기본적으로 JSON 무시됨 @JsonIgnoreExtraProperties (이흐노룬나운 = true)'.
자바 객체를 JSON 제외하려면 필드 / 게터 쓸 때, 이제 '대신' '라는 주석을 @Exclude @JsonIgnore'.
BEFORE
@JsonIgnoreExtraProperties(ignoreUnknown=true)
public class ChatMessage {
public String name;
public String message;
@JsonIgnore
public String ignoreThisField;
}
dataSnapshot.getValue(ChatMessage.class)
AFTER
public class ChatMessage {
public String name;
public String message;
@Exclude
public String ignoreThisField;
}
dataSnapshot.getValue(ChatMessage.class)
Json 에 포함되지 않은 경우 추가 너회의 Java 클래스, 속성 로그 파일에서 이 경고에는 볼 수 있습니다.
W/ClassMapper: No setter/field for ignoreThisProperty found on class com.firebase.migrationguide.ChatMessage
없앨 수 있습니다 '경고' 를 두고 있는 이 @IgnoreExtraProperties 주석 구분된다. 스케쳐내 중포 기지 동작할 수 있는 데이터베이스 때와 마찬가지로 2.x SDK 와 예외가 알 수 없는 경우 ',' @ThrowOnExtraProperties 클래스에 대한 속성 주석 저장할 수 있습니다.