【问题标题】:create json using Google Gson使用 Google Gson 创建 json
【发布时间】:2017-04-22 10:57:12
【问题描述】:

我要制作 json

records":[ {"MON_PRIORITY":"","MON_ICR_ACCNO":"100000010010","MON_REPORT_DATE":"","MON_STATUS":"",

但是我的json是

   {"MON_PRIORITY":"","MON_ICR_ACCNO":"100000010010","MON_REPORT_DATE":"","MON_STATUS":"",

我的jsp代码是

HashMap  jsonRecordval = (HashMap) hshValues.get("jsonRecord");
String json="";
json = new Gson().toJson(jsonRecordval );

谢谢..

【问题讨论】:

  • 在使用集合 API 时始终使用泛型,这样你的代码会更干净。让我知道键和值数据类型。

标签: java json jsp jakarta-ee


【解决方案1】:

您得到的是由 Hashmap 生成的 JSON。例如{"key":"value"}。把它分解成什么,你想要的json是一个对象{的表示,它有一个记录字段"records",其中包含一个数组[你的hashmap的内容{"key":"value"}

为此,最简单的方法是创建一个对象,其实例变量对应于预期输出的字段。类似的东西

public class JsonRecords {
    private final List<HashMap> records = new ArrayList<>;

    public JsonRecords(HashMap recordsVal) {
        records.add(recordsVal);
    }

    //Getters and setters
}

然后用它来构建你的 JSON

HashMap  jsonRecordval = (HashMap) hshValues.get("jsonRecord");
String json = new Gson().toJson(new JsonRecords(jsonRecordval));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-14
    • 2023-03-16
    • 2011-01-03
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多