Java Class for obtaining corresponding Gson json object

119 Views Asked by At

I have a json object with following representation :

{
    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]]],
    ], };

I need to create a Java Class that can be used to create JSON with above structure using Gson.

This is what I currently have:

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;
    }
}

Above class works for serializing text field but I am not sure what datatype I need to use for entities so that it creates an array of array of triplets with form "['T1', 'Person', [[0, 11]]]".

1

There are 1 best solutions below

2
On BEST ANSWER

your code is fine for the Json provided.

however:

The entities is a mix of types.

each entity in entities is an Array.

There are 3 element in an entity: String, String and Array

This is not the recommended way. i would suggest to use:

{
    "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
                ]
            ]
        }
        ...
    ]
}

in this case you will have 2 Pojo's:

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;
}