How to answer a json using Gson

Asked

Viewed 104 times

1

First of all, I agree that the question has gotten a little strange, but I can’t write my question otherwise. At the end of the explanation of the problem if someone wants to suggest a better title that better expresses the problem I will be grateful.

Come on. I got one today map with values as follows:

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

I apply the library Gson and I get the following json:

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

But what I need is: (Look at the square brackets []):

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

What I need to do to get the json come with the clasps?

I saw this question on stack. Has relationship with my problem.

  • 2

    The format you need is not a valid JSON format. Vc is consuming some API that requires this format?

  • 1

    [] are usually used to represent collections. Have you tried a Map<String, List<Pessoa>>, Map<String, Pessoa[]> or Map<String, List<Map<String, Serializable>>>?. Addition example: map.put("max", Collections.singleton(mapaPessoa1). I don’t know exactly how you’re doing the marshalling but one of these options should come close to what you want.

  • @Anthonyaccioly I’ll try your alternatives

  • Reinforce the @Leonardolima justification. The structure you want does not represent a JSON format. The closest you can get to this is "min": [{"name": "so-and-so", "age": 10}].

1 answer

4


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

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

Alternative 1: You can do a new analysis on the structure you need, it doesn’t seem that makes much sense the way you are using it.

Alternative 2: You replace the Person attributes for a List.

Alternative 3: You can use http://www.jsonschema2pojo.org/, as a model parameter.

Big hug and good luck.

  • I’ll try your alternatives. Originated

Browser other questions tagged

You are not signed in. Login or sign up in order to post.