Jackson ResourceAccessException:I / O错误:无法识别的字段

时间:2012-04-16 13:12:16

标签: java json jackson

我有这个json文件

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

所以这是一个Foo实体数组。

然后我有了我的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: java.io.ByteArrayInputStream@554d7745; line: 3, column: 14] (through reference chain: org.my.package.impl.Foo["foo"]); 

1 个答案:

答案 0 :(得分:2)

Exception表示它正在尝试将JSONObject(最高级别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抱怨

  

无法识别的字段“foo”(类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));
}