【问题标题】:How to create multi level JSON data using JSONObject in servlet如何在 servlet 中使用 JSONObject 创建多级 JSON 数据
【发布时间】:2017-08-12 12:21:00
【问题描述】:

我需要创建如下 JSON 数据,

{
  "min": {
    "week": "1",
    "year": "2014"
  },
  "max": {
    "week": "14",
    "year": "2017"
  }
}

但是 JSONObject 只接受 "id","value" 格式。 那么如何使用上面提到的 JSONObject 创建 JSON 数据。

【问题讨论】:

    标签: java json servlets multi-level


    【解决方案1】:

    已经在 Eclipse 中为您测试过了。 `

    String s = "{ \"min\": { \"week\": \"1\", \"year\": \"2014\" }, \"max\": { \"week\": \"14\", \"year\": \"2017\" } }";
    JSONParser parser = new JSONParser();
    try {
        JSONObject json = (JSONObject) parser.parse(s);
        System.out.println(json.get("min"));
        // this will output
        //{"week":"1","year":"2014"}
    } catch (Exception e){
        e.printStackTrace();
    }
    

    `

    【讨论】:

      【解决方案2】:

      这很容易,这里有一个例子:

      JSONObject min = new JSONObject();
      min.put("week", "1");
      min.put("year", "2014");
      
      JSONObject max = new JSONObject();
      max.put("week", "14");
      max.put("year", "2017");
      
      JSONObject json= new JSONObject();
      stats.put("min", min);
      stats.put("max", max);
      
      System.out.println(json.toString());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-24
        • 1970-01-01
        • 1970-01-01
        • 2018-08-15
        • 2018-06-13
        • 2015-11-13
        • 2014-01-23
        • 2016-06-27
        相关资源
        最近更新 更多