How to construct a json answer using Gson

1

First of all, I agree that the question was a bit strange, but I can not write my question any other way. At the end of the explanation of the problem if someone wants to suggest a better title that expresses the problem better, I will be grateful.

Come on. Today I have a map with values as follows:

HashMap<String, Pessoa> map = new HashMap<>();
map.put("max", pessoa1);
map.put("min", pessoa2);

I run the Gson library and get the following json:

{
    "min": {
        "name": "Fulano",
        "age": 10,
    },
    "max": {
        "name": "Siclano",
        "age": 13
    }
}

But what I need is: (Note the brackets [] ):

{
    "min": [
        "name": "Fulano",
        "age": 10,
    ],
    "max": [
        "name": "Siclano",
        "age": 13
    ]
}

What do I need to do to get json with the brackets?

I saw this question in stack . You have relation to my problem.

    
asked by anonymous 22.09.2018 / 16:43

1 answer

4

Notice a detail, your Map reference Person, so the representation of your JSON will treat each item as an independent item. The fact that it is Map forces this because it is a highly dynamic object.

Another detail is that you need the representation of an Array [], but you are being forced to represent an object {}, because when you put in the Map, a new object is added.

Alternative 1: You can do a new analysis on the structure you need, it does not seem to make much sense the way you are using it.

Alternative 2: You override the attributes of Person for a List.

Alternative 3: You can use the link as a modeling parameter.

Big hug and good luck.

    
24.09.2018 / 18:25