用于获取相应Gson json对象的Java类

时间:2015-06-14 10:25:45

标签: java json gson

我有一个带有以下表示的json对象:

{
    text     : "Ed O'Kelley was the man who shot the man who shot Jesse James.",
    entities : [
        ['T1', 'Person', [[0, 11]]],
        ['T2', 'Person', [[20, 23]]],
        ['T3', 'Person', [[37, 40]]],
        ['T4', 'Person', [[50, 61]]],
    ], };

我需要创建一个Java类,可以使用Gson创建具有上述结构的JSON。

这就是我目前所拥有的:

public class DocData
{
    private String text;

    private List<List<String>> entities;

    public DocData(final String text, final List<List<String>> entities)
    {
        this.text = text;
        this.entities = entities;
    }

    public List<List<String>> getEntities()
    {
        return entities;
    }
}

上面的类适用于序列化text字段,但我不确定我需要为entities使用什么数据类型,以便它创建一个形式为"['T1', 'Person', [[0, 11]]]"的三元组数组。< / p>

1 个答案:

答案 0 :(得分:2)

您的代码适用于所提供的Json

但是:

entities是各种类型。

entity中的每个entities都是Array

entity中有3个元素:StringStringArray

这不是推荐的方法。我建议使用:

{
    "text": "Ed O'Kelley was the man who shot the man who shot Jesse James.",
    "entities": [
        {
            "field_name_1": "T1",
            "field_name_2": "Person",
            "field_name_3": [
                [
                    0,
                    11
                ]
            ]
        }
        ...
    ]
}

在这种情况下,您将有2 Pojo个:

public class DocData
{
    private String text;

    private List<Entity> entities;

    public DocData(final String text, final List<Entity> entities)
    {
        this.text = text;
        this.entities = entities;
    }

    public List<Entity> getEntities()
    {
        return entities;
    }
}


public class Entity
{
    private String field_name_1;

    private String field_name_2;

    private List<List<Integer>> field_name_3;
}