Reputation: 542
This is JSON file. I want make java can produce like this json. Just ignore the value, What i want is the structure of the 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
}
]
}
This is my java code.
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();
}
The output is :
{
"Car": [
{
"Motor": [
{
"MotorId": 0,
"DriverId": 0
}
]
},
{
"Bus": [
{
"BusId": 0,
"Status": 0
}
]
}
]
}
For value, it's okay, just ignore the value, but what i want how can i get structure like the json file.
Upvotes: 2
Views: 3261
Reputation: 218
JSONObject motorObject = new JSONObject();
JSONObject busObject = new JSONObject();
JSONObject carObject = new JSONObject();
JSONObject wholeObject =new JSONObject();
JSONArray motorArray = new JSONArray();
JSONArray busArray = new JSONArray();
JSONArray carArray = new JSONArray();
motorArray.put(motorTracks.getJSONObject());
busArray.put(buss.getJSONObject());
carArray.put(car.getJSONObject());
try
{
wholeObject.put("Motor",motorArray);
wholeObject.put("Bus",busArray);
wholeObject.put("Car",carArray);
System.out.println(wholeObject);
}
catch (JSONException e)
{
e.printStackTrace();
}
Upvotes: 1
Reputation: 2577
Use this code and Enjoy :)
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();
}
}
Upvotes: 2