有没有一种简单的方法可以将字符串列表反序列化为单个字符串?例如,我将使用以下JSON:{ "stringList": [ "somethingElse" ], "simpleString": "something",}我希望将其反序列化到此POJO中:@Data@JsonIgnoreProperties(ignoreUnknown = true)public class AClass { @JsonProperty("stringList") private String justAString; @JsonProperty("simpleString") private String someString;}我想提一下,可以肯定的是,该列表只有一项,并且无法控制其生成方式。是为justAString字段添加自定义反序列化器的唯一方法吗?编辑如果可能的话,我想使用Jackson的ObjectMapper类 最佳答案 一种方法是对需要转换的属性使用备用的getter / setter方法,即将@JsonProperty注释从字段移至getter方法,添加额外的一组getter / setter方法,并使用@JsonIgnore,因此不使用它们:class AClass { private String justAString; private String someString; @JsonProperty // JSON field named same as virtual property private List<String> getStringList() { // Getter for virtual property (private = hidden from Java callers) return Collections.singletonList(this.justAString); } private void setStringList(List<String> stringList) { // Setter for virtual property this.justAString = stringList.toString(); } @JsonIgnore // This POJO property is not a JSON field public String getJustAString() { // Standard POJO getter return this.justAString; } public void setJustAString(String justAString) { // Standard POJO setter this.justAString = justAString; } @JsonProperty("simpleString") // JSON field named different from POJO property public String getSomeString() { // Standard POJO getter return this.someString; } public void setSomeString(String someString) { // Standard POJO setter this.someString = someString; }}测试String input = "{\r\n" + " \"stringList\": [\r\n" + " \"somethingElse\"\r\n" + " ],\r\n" + " \"simpleString\": \"something\"\r\n" + "}";AClass aClass = new ObjectMapper().readValue(input, AClass.class);System.out.println("justAString = " + aClass.getJustAString());System.out.println("someString = " + aClass.getSomeString());输出量justAString = [somethingElse]someString = something
10-04 19:38