2012-04-16 35 views
1

我有了這個JSON文件傑克遜ResourceAccessException:I/O錯誤:無法識別領域

[ 
    { 
     "foo":{ 
     "comment":null, 
     "media_title":"How I Met Your Mother", 
     "user_username":"nani" 
     } 
    }, 
    { 
     "foo":{ 
     "comment":null, 
     "media_title":"Family Guy", 
     "user_username":"nani" 
     } 
    } 
] 

所以這是富實體的陣列。

然後,我有我的Foo對象:

import org.codehaus.jackson.annotate.JsonProperty; 
    import org.codehaus.jackson.map.annotate.JsonRootName; 

    @JsonRootName("foo") 
    public class Foo { 

     @JsonProperty 
     String comment; 
     @JsonProperty("media_title") 
     String mediaTitle; 
     @JsonProperty("user_username") 
     String userName; 

/** setters and getters go here **/ 

    } 

然後我有我我FooTemplate如下:

public List<Foo> getFoos() { 
    return java.util.Arrays.asList(restTemplate.getForObject(buildUri("/foos.json"), 
      Foo[].class)); 
} 

但是當我運行我的簡單測試,我得到:

org.springframework.web.client.ResourceAccessException: I/O error: Unrecognized field "foo" (Class org.my.package.impl.Foo), not marked as ignorable at [Source: [email protected]; line: 3, column: 14] (through reference chain: org.my.package.impl.Foo["foo"]); 

回答

2

Exception表明它試圖反序列化JSONObject(第th at是頂級JSONArray)的元素轉換爲Foo對象。因此,您沒有一個Foo實體數組,您有一個具有Foo成員的對象數組。

這裏是什麼ObjectMapper正在試圖做的事:

[ 
    {   <---- It thinks this is a Foo. 
     "foo":{ <---- It thinks this is a member of a Foo. 
     "comment":null, 
     "media_title":"How I Met Your Mother", 
     "user_username":"nani" 
     } 
    }, 
    {   <---- It thinks this is a Foo. 
     "foo":{ <---- It thinks this is a member of a Foo. 
     "comment":null, 
     "media_title":"Family Guy", 
     "user_username":"nani" 
     } 
    } 
] 

正是因爲這一點的Exception抱怨

Unrecognized field "foo" (Class org.my.package.impl.Foo)

也許你想取出第一JSONObject,和擺脫foo標識符。

[ 
    { 
     "comment":null, 
     "media_title":"How I Met Your Mother", 
     "user_username":"nani" 
    }, 
    { 
     "comment":null, 
     "media_title":"Family Guy", 
     "user_username":"nani" 
    } 
] 

編輯

您也可以創建一個新的Bar對象,將舉行一個Foo實例,並試圖來解讀到一個數組。

class Bar { 
    @JsonProperty 
    private Foo foo; 

    // setter/getter 
} 

public List<Bar> getBars() { 
    return java.util.Arrays.asList(restTemplate.getForObject(buildUri("/foos.json"), 
      Bar[].class)); 
} 
+0

不幸的是,它不是「我自己的」json。我也認爲這是一種破碎的JSON,但由於它是公共API,我就像「不能......」。我猜應該問問這些人。也許它實際上是他們的錯誤 – user1168098 2012-04-16 14:10:32

+0

看看我的編輯另一個建議。 – 2012-04-16 14:59:06

+0

好吧。我跟着你的建議和一個只包含Foo對象屬性的FooMixin對象。謝謝 – user1168098 2012-04-17 07:23:46