根据我的阅读,下面的例子是JSONArray
。
我最为困惑的是添加顶部"标题"信息和嵌套"位置" JSONObject作为最后一个属性。我知道如何创建一个基本的JSONObject,以及一个基本的JSONArray,但这个组合的实际上是让我失望。
{
"source": "REMOTE",
"msgType": "event",
"properties": [
{
"IMEI": {
"string": "1234567890"
}
},
{
"My Time": {
"string": "5/4/2016 12:00:00"
}
},
{
"Position": {
"geographicPosition": {
"latitude": 34.89767579999999,
"longitude": -72.03648269999997
}
}
}
]
}
答案 0 :(得分:2)
试试这个:
try {
JSONObject mainObject = new JSONObject();
mainObject.put("source", "REMOTE");
mainObject.put("msgType", "event");
JSONArray mainArray = new JSONArray();
JSONObject arrayObj = new JSONObject();
JSONObject temp = new JSONObject();
temp.put("string", "1234567890");
arrayObj.put("IMEI", temp);
mainArray.put(arrayObj);
arrayObj = new JSONObject();
temp = new JSONObject();
temp.put("string", "5/4/2016 12:00:00");
arrayObj.put("My Time", temp);
mainArray.put(arrayObj);
arrayObj = new JSONObject();
temp = new JSONObject();
JSONObject temp1 = new JSONObject();
temp1.put("latitude",34.89767579999999);
temp1.put("longitude",-72.03648269999997);
temp.put("geographicPosition", temp1);
arrayObj.put("Position", temp);
mainArray.put(arrayObj);
mainObject.put("properties", mainArray);
// mainOject is your required Json
System.out.println(mainObject);
} catch (Exception e) {
e.printStackTrace();
}
答案 1 :(得分:0)
你也可以这样做..
user_id
答案 2 :(得分:0)
尝试伟大的oracle documentation。他们有一个示例,展示了如何创建数组。这是他们想要创建的模板:
{
"firstName": "John", "lastName": "Smith", "age": 25,
"address" : {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
他们是如何做到的:
\\ You can pass `null` to the `config`
JsonBuilderFactory factory = Json.createBuilderFactory(config);
JsonObject value = factory.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Smith")
.add("age", 25)
.add("address", factory.createObjectBuilder()
.add("streetAddress", "21 2nd Street")
.add("city", "New York")
.add("state", "NY")
.add("postalCode", "10021"))
.add("phoneNumber", factory.createArrayBuilder()
.add(factory.createObjectBuilder()
.add("type", "home")
.add("number", "212 555-1234"))
.add(factory.createObjectBuilder()
.add("type", "fax")
.add("number", "646 555-4567")))
.build();