如何使用JSONObject java创建以下JSON?

问题描述 投票:-5回答:1

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

{
    cars: [{
            car: {},
            brands: ["C", "D"]
        }
    ]
}
java json
1个回答
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"
      ]
    }
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.