【问题标题】:Jackson parsing error: exception org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "Results"杰克逊解析错误:异常 org.codehaus.jackson.map.exc.UnrecognizedPropertyException:无法识别的字段“结果”
【发布时间】:2019-08-09 17:00:42
【问题描述】:

有一些这样的主题,但是我已经阅读了所有内容,但仍然没有运气。

我有一个类用于反序列化来自 Web 服务的一些 JSON 响应。简而言之,我花了太多时间来研究这个问题,我希望有人能找出我的方法的错误。根据标题,我使用的是 Jackson 库。

以下类的片段:

final class ContentManagerResponse implements Serializable {

    @JsonProperty("Results")
    private List<OrgSearchResult> results = null;
    @JsonProperty("PropertiesAndFields")
    private PropertiesAndFields propertiesAndFields;
    @JsonProperty("TotalResults")
    private Integer totalResults;
    @JsonProperty("CountStringEx")
    private String countStringEx;
    @JsonProperty("MinimumCount")
    private Integer minimumCount;
    @JsonProperty("Count")
    private Integer count;
    @JsonProperty("HasMoreItems")
    private Boolean hasMoreItems;
    @JsonProperty("SearchTitle")
    private String searchTitle;
    @JsonProperty("HitHighlightString")
    private String hitHighlightString;
    @JsonProperty("TrimType")
    private String trimType;
    @JsonProperty("ResponseStatus")
    private ResponseStatus responseStatus;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("Results")
    public List<OrgSearchResult> getResults() {
        return results;
    }

    @JsonProperty("Results")
    public void setResults(List<OrgSearchResult> results) {
        this.results = results;
    }
        //additional getters and setters.

如前所述,Results 是似乎有错误的属性。

JSON 响应如下。

{
    "Results": [
        {
            "TrimType": "Location",
            "Uri": 1684
        }
    ],
    "PropertiesAndFields": {},
    "TotalResults": 1,
    "CountStringEx": "1 Location",
    "MinimumCount": 1,
    "Count": 0,
    "HasMoreItems": false,
    "SearchTitle": "Locations - type:Organization and id:24221",
    "HitHighlightString": "",
    "TrimType": "Location",
    "ResponseStatus": {}
}

我正在使用同一个类来反序列化以下响应并且它有效:

{
    "Results": [
        {
            "LocationIsWithin": {
                "Value": true
            },
            "LocationSortName": {
                "Value": "GW_POS_3"
            },
            "LocationTypeOfLocation": {
                "Value": "Position",
                "StringValue": "Position"
            },
            "LocationUserType": {
                "Value": "RecordsWorker",
                "StringValue": "Records Co-ordinator"
            },
            "TrimType": "Location",
            "Uri": 64092
        }
    ],
    "PropertiesAndFields": {},
    "TotalResults": 1,
    "MinimumCount": 0,
    "Count": 0,
    "HasMoreItems": false,
    "TrimType": "Location",
    "ResponseStatus": {}
}

错误信息是否只是误导?除了第二个(工作)有效负载没有类中的某些字段之外,该结构是相同的。我希望这个会出错。

为了它的价值,我还在下面添加了 OrgSearchResult 类:

final class OrgSearchResult implements Serializable {

    @JsonProperty("TrimType") private String trimType;
    @JsonProperty("Uri") private String uri;
    @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>();
        //getters and setters

很多故障排除。我什至尝试使用忽略属性似乎无法让它们工作。

完全错误:

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: 无法识别的字段“结果”(类 sailpoint.doet.contentmanager.ContentManagerResponse),未标记为 [来源:java.io.StringReader@5c6648b0;行:1,列: 13](通过引用链: 帆点.doet.contentmanager.ContentManagerResponse["结果"])

【问题讨论】:

    标签: java json jackson deserialization json-deserialization


    【解决方案1】:

    您可以使用PropertyNamingStrategy.UPPER_CAMEL_CASE 策略提高POJO 类的可读性。此外,您可以使用 JsonAnySetter 注释来读取所有额外的属性。下面的示例显示了模型的外观:

    import com.fasterxml.jackson.annotation.JsonAnySetter;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.PropertyNamingStrategy;
    
    import java.io.File;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class JsonApp {
    
        public static void main(String[] args) throws Exception {
            File jsonFile = new File("./resource/test.json").getAbsoluteFile();
    
            ObjectMapper mapper = new ObjectMapper();
            mapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
    
            System.out.println(mapper.readValue(jsonFile, ContentManagerResponse.class));
        }
    
    }
    
    class ContentManagerResponse {
    
        private List<OrgSearchResult> results;
        private Map<String, Object> propertiesAndFields;
        private Integer totalResults;
        private String countStringEx;
        private Integer minimumCount;
        private Integer count;
        private Boolean hasMoreItems;
        private String searchTitle;
        private String hitHighlightString;
        private String trimType;
        private Map<String, Object> responseStatus;
    
        // getters, setters, toString
    }
    
    class OrgSearchResult {
    
        private String trimType;
        private String uri;
    
        private Map<String, Object> additionalProperties = new HashMap<>();
    
        @JsonAnySetter
        public void additionalProperties(String name, Object value) {
            additionalProperties.put(name, value);
        }
    
        // getters, setters, toString
    }
    

    对于上面代码打印的第一个 JSON 有效负载:

    ContentManagerResponse{results=[OrgSearchResult{trimType='Location', uri='1684', additionalProperties={}}], propertiesAndFields={}, totalResults=1, countStringEx='1 Location', minimumCount=1, count=0, hasMoreItems=false, searchTitle='Locations - type:Organization and id:24221', hitHighlightString='', trimType='Location', responseStatus='{}'}
    

    对于第二个JSON 有效载荷上面的代码打印:

    ContentManagerResponse{results=[OrgSearchResult{trimType='Location', uri='64092', additionalProperties={LocationSortName={Value=GW_POS_3}, LocationUserType={Value=RecordsWorker, StringValue=Records Co-ordinator}, LocationIsWithin={Value=true}, LocationTypeOfLocation={Value=Position, StringValue=Position}}}], propertiesAndFields={}, totalResults=1, countStringEx='null', minimumCount=0, count=0, hasMoreItems=false, searchTitle='null', hitHighlightString='null', trimType='Location', responseStatus='{}'}
    

    你不需要实现Serializable接口。

    【讨论】:

    • 非常感谢。在查看了您的示例与我的示例之后,我意识到我正在导入不同的 ObjectMapper (org.codehaus.jackson.map.ObjectMapper),即使我所有的注释导入都与您的相同。只需将我的 ObjectMapper 导入从 'org.codehaus.jackson.map.ObjectMapper' 更改为 'com.fasterxml.jackson.databind.ObjectMapper' 就可以消除我的错误。
    猜你喜欢
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 2018-08-25
    • 1970-01-01
    • 2015-09-28
    相关资源
    最近更新 更多