1

我有这个 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"]); 
4

1 回答 1

2

Exception表明它正在尝试将JSONObject's (那些是顶级元素的元素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));
}
于 2012-04-16T13:57:25.797 回答