Generowanie JSON w Java

0

Jak wygenerować taki kod JSON

{
    "rowsPerPage": 10,
    "page": 1,
    "total": 100,      
    "rows": [
            {
                "id": 1,
                "name": "name1"
            },
            {
                "id": 2,
                "name": "name2"
            },
            {
                "id": 3,
                "name": "name3"
            }
        ]
}

Mam coś takiego

ModelMap modelMap = new ModelMap();
            modelMap.put("rowsPerPage", 10);
            modelMap.put("page", 1);
            modelMap.put("total", 100);

Ale nie wiem jak dodać rows?

1

Zrób sobie obiekt pojo a nastepnie z niego jsona.

 
public MyPojo{
  private int rowsPerPage;
  private int page;
  private int total;      
  private Object rows;
 
  ... gett and sett

}

MyPojo pojo = new MyPojo();
pojo.setRows(modelMap);

I ustaw resztę względem tego co chcesz. A później użyj czegoś co Tobie zamieni obiekt pojo na JSON-a. Np. Gsona googlowego.

0
public class Model {

    private int rowsPerPage;
    private int page;
    private int total;
    private List<Row> rows;

    public Model(int rowsPerPage, int page, int total) {
        this.rowsPerPage = rowsPerPage;
        this.page = page;
        this.total = total;
    }

    public void addRow(Row row) {
        if (rows == null) {
            rows = new ArrayList<Row>();
        }
        this.rows.add(row);
    }

//setters getters 
    
}

public class Row {

    private int id;
    private String name;

    public Row(int id, String name) {
        this.id = id;
        this.name = name;
    }

    //setters getters
}

public class App {

    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Model model = new Model(10, 1, 100);
        model.addRow(new Row(1, "name1"));
        model.addRow(new Row(2, "name2"));
        model.addRow(new Row(3, "name3"));
        System.out.println(gson.toJson(model));
    }
}

Jak widać do wygenerowania jsona użyłem tutaj Gson od Google

1 użytkowników online, w tym zalogowanych: 0, gości: 1