这是 JSON 文件。我想让java可以生成这样的json。忽略该值,我想要的是 json 的结构。
{
"Car": [
{
"CarId": 123,
"Status": "Ok"
},
{
"CarId": 124,
"Status": "ok"
}
],
"Motor": [
{
"MotorId": 3,
"DriverId": 174
},
{
"MotorId": 3,
"DriverId": 174
}
],
"Bus": [
{
"BusId": 8,
"Status": 3
},
{
"BusId": 9,
"Status": 2
}
]
}
这是我的java代码。
JSONObject motorObject = new JSONObject();
JSONObject busObject = new JSONObject();
JSONObject carObject = new JSONObject();
JSONArray motorArray = new JSONArray();
JSONArray busArray = new JSONArray();
JSONArray carArray = new JSONArray();
motorArray.put(motorTracks.getJSONObject());
busArray.put(buss.getJSONObject());
try
{
motorObject.put("Motor",motorArray);
busObject.put("Bus",busArray);
carArray.put(MotorObject);
carArray.put(stepObject);
carObject.put("Car",dataArray);
} catch (JSONException e)
{
e.printStackTrace();
}
输出是:
{
"Car": [
{
"Motor": [
{
"MotorId": 0,
"DriverId": 0
}
]
},
{
"Bus": [
{
"BusId": 0,
"Status": 0
}
]
}
]
}
对于值,没关系,忽略该值即可,但是我想要的是如何获得像json文件这样的结构。
最佳答案
使用此代码并享受:)
private void createJsonStructure() {
try
{
JSONObject rootObject = new JSONObject();
JSONArray carArr = new JSONArray();
for (int i = 0; i < 2 ; i++)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("CarId", "123");
jsonObject.put("Status", "Ok");
carArr.put(jsonObject);
}
rootObject.put("Car", carArr);
JSONArray motorArr = new JSONArray();
for (int i = 0; i < 2 ; i++)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("MotorId", "123");
jsonObject.put("Status", "Ok");
motorArr.put(jsonObject);
}
rootObject.put("Motor", motorArr);
JSONArray busArr = new JSONArray();
for (int i = 0; i < 2 ; i++)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("BusId", "123");
jsonObject.put("Status", "Ok");
busArr.put(jsonObject);
}
rootObject.put("Bus", busArr);
Log.e("JsonObject", rootObject.toString(4));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
关于java - 如何在java android中构造多个对象和JSON数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43316393/