当JAXB用作HashMap密钥时,为什么要编组无法使用的类实例?

时间:2017-12-22 21:48:02

标签: json xml jaxb

在我的restful API中,我使用json-jackson来生成JSON输出。所以我有JAXB-annotatied类:

@XmlRootElement(name = "Vertex")
@XmlType(propOrder = { "id", "label" })
@XmlAccessorType(XmlAccessType.NONE)
public class RepresentedVertex implements Vertex
{
    private Vertex originalVertex;

    @XmlAttribute(name = "id")
    public String getId()
    {
        return this.id().toString();
    }

    @XmlAttribute(name = "label")
    public String getLabel()
    {
        return this.label();
    }


    public RepresentedVertex(Vertex originalVertex)
    {
    super();
    this.originalVertex = originalVertex;
    }

    ...

    @Override
    public String toString()
    {
        StringBuffer buf = new StringBuffer();
        buf.append("[").append(this.getId()).append("::").append(this.getLabel()).append("]");

        return buf.toString();
    }

当我返回带有entity = List<RepresentedVertex>的Response时,一切正常 - 我根据带注释的get-methods获得带有 id label 值的JSON

但是当我返回包含DelegsentedVertex作为键的Map<RepresentedVertex,List <RepresentedVertex>>时 - 我得到了RepresentedVertex.toSting()方法的结果输出(即[1245311 :: testLabel])这样的Map键:

{
    "status": "OK",
    "message": "Ok complete",
    "content": {
        "[1245311::testLabel]": [
            {
                "id": "163852352",
                "label": "dataset"
            },
            {
                "id": "163864664",
                "label": "dataset"
            }
        ]
    }
}

...但我想要单独的 id 标签这样的值:

{
    "status": "OK",
    "message": "Ok complete",
    "content": {
        "vertex": { "id": "1245311",  "label": "testLabel"}: [
            {
                "id": "163852352",
                "label": "dataset"
            },
            {
                "id": "163864664",
                "label": "dataset"
            }
        ]
    }
}

在这种情况下,使用Map键的jaxb表示有什么问题?

1 个答案:

答案 0 :(得分:0)

...所以,正如评论中所指出的,我期待的不是正确的JSON。 所以我为Map创建了JAXB annotaited包装类,并获得如下输出:

{
    "status": "OK",
    "message": "Ok complete",
    "content": {
        "pairs": [{
            "vertex": {
                "id": "1245311",
                "label": "testLabel"
            },
            "objects": [{
                    "id": "163852352",
                    "label": "dataset"
                },
                {
                    "id": "163864664",
                    "label": "dataset"
                }
            ]
        }]
    }
}