gpt4 book ai didi

java - 在java中从列表转换为json

转载 作者:行者123 更新时间:2023-11-29 04:46:16 25 4
gpt4 key购买 nike

我有一个列表,我想将其转换为 json。

这是我的代码

JqGridModel gridModel1 = new JqGridModel();
Date FromDate = new Date("1996-07-04");
Date ToDate = new Date("1996-07-05");
gridModel1.setOrderID(10248);
gridModel1.setFromDate(FromDate);
gridModel1.setToDate(ToDate);
gridModel1.setCustomerID("WILMK");
gridModel1.setShipName("Vins et alcools Chevalier");

JqGridModel gridModel2 = new JqGridModel();
Date FromDate2 = new Date("1996-07-04");
Date ToDate2 = new Date("1996-07-05");
gridModel2.setOrderID(10248);
gridModel2.setFromDate(FromDate2);
gridModel2.setToDate(ToDate2);
gridModel2.setCustomerID("WILMK");
gridModel2.setShipName("Vins et alcools Chevalier");



List jqGridModels = new ArrayList();
jqGridModels.add(gridModel1);
jqGridModels.add(gridModel2);

我想将其转换为以下格式:

{ 
"rows":[
{"OrderID":"10248","FromDate":"1996-07-04","CustomerID":"WILMK","ShipName":"Vins et alcools Chevalier","ToDate":"1996-07-05"},
{"OrderID":"10249","FromDate":"1996-07-05","CustomerID":"TRADH","ShipName":"Toms Spezialit\u00e4ten","ToDate":"1996-07-17"},
{"OrderID":"10250","FromDate":"1996-07-08","CustomerID":"HANAR","ShipName":"Hanari Carnes","ToDate":"1996-07-26"},
{"OrderID":"10251","FromDate":"1996-07-08","CustomerID":"VICTE","ShipName":"Victuailles en stock","ToDate":"1996-08-01"},
{"OrderID":"10252","FromDate":"1996-07-09","CustomerID":"SUPRD","ShipName":"Supr\u00eames d\u00e9lices","ToDate":"1996-08-01"}
]
}

如有任何帮助,我们将不胜感激。

最佳答案

首先:使用泛型

List jqGridModels = new ArrayList();  //bad
List<JqGridModel> jqGridModels = new ArrayList<>(); //good

其次:会不会用Gson?

List<JqGridModel> jqGridModels = new ArrayList<>();

Gson gson = new Gson();
JsonElement jsElem = gson.toJsonTree(jqGridModels, new TypeToken<List<JqGridModel>>() {}.getType());

if (! jsElem.isJsonArray()) {
//this is an error...
}

JsonArray jsonArray = jsElem.getAsJsonArray();

还没有测试过,但应该可以,我正在我的项目中这样做,没关系,如果您有更多问题,请告诉我!

关于java - 在java中从列表转换为json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36998411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com