【问题标题】:Hierarchical POJOs not being properly serialized to JSON by RESTEasy/JacksonRESTEasy/Jackson 未将分层 POJO 正确序列化为 JSON
【发布时间】:2017-05-12 05:59:43
【问题描述】:

我有两个 POJO 定义如下,

public class VertexDefinition {
    private final String name;
    private final Vertex vertex;

    public VertexDefinition(String name, Vertex vertex) {
        this.name = name;
        this.vertex = vertex;
    }

    @JsonProperty("name")
    public String getName() {
        return name;
    }

    @JsonProperty("properties")
    public Iterable<PropertyDefinition> getProperties() {
        if(vertex == null) {
            return Collections.emptySet();
        }
        return Iterables.transform(vertex.getPropertyKeys(), new Function<String, PropertyDefinition>() {
            @Nullable @Override public PropertyDefinition apply(@Nullable String s)  {
                return new PropertyDefinition(vertex, s);
            }
        });
    }

    @JsonProperty("propertyKeys")
    public Iterable<String> getPropertyKeys() {
        if (vertex == null) {
            return Collections.emptySet();
        }
        return vertex.getPropertyKeys();
    }

}

public class PropertyDefinition {

    private final Vertex vertex;
    private final String propertyName;

    public PropertyDefinition(Vertex vertex, String propertyName) {
        this.vertex = vertex;
        this.propertyName = propertyName;
    }

    @JsonProperty("name")
    public String getName() {
        return propertyName;
    }

    @JsonProperty("type")
    public String getType() {
        final Object property = vertex.getProperty(propertyName);

        if (property != null) {
            return property.getClass().getTypeName();
        }

        return "(unknown)";
    }
}

我的 Rest 方法如下所示,

public Iterable<VertexDefinition> getSchema() {
    .....
}

当我发出请求时,我会收到如下的 json 响应,

 [
   {
       "name" : "Foo",
       "properties" : [],
       "propertyKeys" : [
          "a",
          "b",
          "c"
       ]
   },
   {
       "name" : "Bar",
       "properties" : [],
       "propertyKeys" : [
          "a",
          "b",
          "c"
       ]
   }
]

简而言之,我在填写 propertyKeys 时为属性返回了一个空数组。

我做错了什么?

【问题讨论】:

    标签: java json jackson resteasy


    【解决方案1】:

    我不认为你已经尝试过将反序列化为可迭代的工作。你可以在你的getProperties 方法中尝试这样的事情吗?

    List<PropertyDefinition> propertyDefinitions = Arrays.asList(mapper.readValue(json, PropertyDefinition[].class))
    

    【讨论】:

    • 我确实知道这行得通,但我很好奇为什么 Iterable 不适用于我的自定义类型,而它适用于 String。
    • 我认为您可以返回一个可迭代对象,但目前您没有使用任何杰克逊映射器来反序列化您的对象,这是主要问题。看看this link,我想它可能有你要找的东西
    猜你喜欢
    • 2016-08-16
    • 1970-01-01
    • 2011-08-07
    • 2012-04-07
    • 2020-12-10
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多