【问题标题】:How to create following JSON using JSONObject java?如何使用 JSONObject java 创建以下 JSON?
【发布时间】:2018-06-13 17:47:00
【问题描述】:

我需要在 java 中使用 JSONObject 来表示以下 JSON 结构。如何才能做到这一点? 我很困惑,因为 car 是 JSON,brands 是一个数组,它们组合在一起成为“CARS”数组的单个元素。

{
    cars: [{
            car: {},
            brands: ["C", "D"]
        }
    ]
}

【问题讨论】:

标签: java json


【解决方案1】:

你的问题不清楚,但如果你只是想要一个 JSONObject 的例子,那么下面的代码可以生成你想要的。

JSONObject car = new JSONObject();
car.put("car", new JSONObject());

JSONArray brands = new JSONArray();
brands.put("C");
brands.put("D");
car.put("brands", brands);

JSONArray cars = new JSONArray();
cars.put(car);

JSONObject json = new JSONObject();
json.put("cars", cars);

System.out.println(json.toString(2));

输出是

{
  "cars": [
    {
      "car": {},
      "brands": [
        "C",
        "D"
      ]
    }
  ]
}

【讨论】:

    猜你喜欢
    • 2014-11-02
    • 2023-02-24
    • 1970-01-01
    • 2014-03-29
    • 2015-11-13
    • 1970-01-01
    • 2014-06-03
    • 2013-09-29
    • 2022-01-23
    相关资源
    最近更新 更多