Home > Net >  Transform list in a JSON, then adding an header on top of this JSON
Transform list in a JSON, then adding an header on top of this JSON

Time:07-12

I have a list of objects:

List<ScuolaEntity> result = scuolaService.getAllScuoleEntity();

I would like to convert the list in a json object, I have tried with gson, with JSONObject and even with JsonNode, but I couldn't find a way to add a header/node to the json.

This is the actual json:

[
    {
        "codiceMeccanografico": "RMAT123456",
        "codiceFiscale": "CREMHL90T42B745CQQE",
        "denominazione": "ITS INCOM"
    },
    {
        "codiceMeccanografico": "RMAT891011",
        "codiceFiscale": "SCEMQL90T42B735CWQ1",
        "denominazione": "Liceo Scientifico Statale E. Lussu"
    }
]

This is what I would like to achieve

{
  "scuole": [
    {
        "codiceMeccanografico": "RMAT123456",
        "codiceFiscale": "CREMHL90T42B745CQQE",
        "denominazione": "ITS INCOM"
    },
    {
        "codiceMeccanografico": "RMAT891011",
        "codiceFiscale": "SCEMQL90T42B735CWQ1",
        "denominazione": "Liceo Scientifico Statale E. Lussu"
    }
  ]
}

Can I add this header "scuole" with gson library or another?

CodePudding user response:

you can achieve this by wrapping this list into a map:

List<ScuolaEntity> result = scuolaService.getAllScuoleEntity();
Map data=Collections.singletoneMap("scuole",result);

And then encode this map as JSON.

  • Related