RESTEasy / Jackson没有将分层POJO正确地序列化为JSON

时间:2016-12-28 00:17:04

标签: java json jackson resteasy

我有两个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)";
    }
}

My Rest方法如下所示,

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

当我提出请求时,我得到如下的json响应,

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

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

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我不认为反序列化成为可迭代的,因为您已尝试过。您可以在getProperties方法中尝试这样的方法吗?

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