2

我有一个有点奇怪的问题。我创建了一个对象,我们称之为 Profile,它通过我调用的 API 成功解析单个 JSON 对象。还有一个多配置文件接口,它将返回配置文件对象的 JSON 数组。问题是,多配置文件接口将子对象转换为字符串。有没有一种自动方法可以告诉杰克逊将这些解析为对象?

单个对象的示例: { "foo": "bar" }

多对象示例: [ "{ \"foo\": \"bar\" }", "{ \"blah\": \"ugh\" }" ]

(抱歉不能使用真实数据)

请注意,子对象实际上是字符串,其中包含转义引号。

为了完整起见,我的多对象解析代码如下所示:

ObjectMapper mapper = new ObjectMapper();
Profile[] profile_array = mapper.readValue(response.content, Profile[].class);
for (Profile p: profile_array)
{
    String user = p.did;
    profiles.put(user, p);
}

正如我所说,在单配置文件的情况下,配置文件对象会解析。在多配置文件的情况下,我得到了这个例外:

Exception: org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.xyz.id.profile.Profile, problem: no suitable creator method found to deserialize from JSON String
4

3 回答 3

2

I suppose you'll have to create a custom deserializer and apply it to the every element of that array.

class MyCustomDeserializer extends JsonDeserializer<Profile> {
    private static ObjectMapper om = new ObjectMapper();

    @Override
    public Profile deserialize(JsonParser jp, DeserializationContext ctxt) {
        // this method is responsible for changing a single text node:
        // "{ \"foo\": \"bar\" }"
        // Into a Profile object

        return om.readValue(jp.getText(), Profile.class);
    }
}
于 2012-06-12T00:09:34.723 回答
0

Have you tried using JAXB?

            final ObjectMapper mapper = new ObjectMapper();

            // Setting up support of JAXB
            final AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();

            // make deserializer use JAXB annotations (only)
            mapper.getDeserializationConfig().setAnnotationIntrospector(
                    introspector);

            // make serializer use JAXB annotations (only)
            mapper.getSerializationConfig().setAnnotationIntrospector(
                    introspector);

            final StringReader stringReader = new StringReader(response);
            respGetClasses = mapper.readValue(stringReader,
                    FooBarClass.class);

The above should get you started...

Also, you would need to mark each subclass like so:

@XmlElement(name = "event")
public List<Event> getEvents()
{
    return this.events;
}
于 2012-06-12T00:07:35.500 回答
0

对嵌入的 JSON-in-JSON 内容的“重新解析”没有开箱即用的支持。但这听起来像是一个可能的增强请求(RFE)......

于 2012-06-12T18:13:22.580 回答