如何使用JSONObject和JSONArray类型创建JSON对象和JSON数组以匹配此格式?

{"PeripheralList":
  [{"Category":"BP","CollectionTime":"2015-12-28T09:09:22-05:00",
    "DeviceInfo":null,
    "Readings":[
            [{"Name":"SYS","Type":"INT","Value":"200"},
            {"Name":"DIA","Type":"INT","Value":"199"},
            {"Name":"HTR","Type":"INT","Value":"102"},
            {"Name":"READINGTIME","Type":"DATETIME","Value":"2015-12-27T08:12:53-05:00"}]
        ]},

{"Category":"HR","CollectionTime":"2015-12-28T09:09:22-05:00",
    "DeviceInfo":[{"Name":"UNITS","Value":"Rate"}],
    "Readings":[
            [{"Name":"HR","Type":"DECIMAL","Value":"200.7"},
            {"Name":"READINGTIME","Type":"DATETIME","Value":"2015-12-27T07:26:49-05:00"}],

            [{"Name":"HR","Type":"DECIMAL","Value":"155.2"},
            {"Name":"READINGTIME","Type":"DATETIME","Value":"2015-12-27T14:39:11-05:00"}]
        ]}
]}


任何帮助,将不胜感激。谢谢。

最佳答案

您应该能够将JSON字符串直接传递给构造函数。

JSONObject mainObject = new JSONObject(jsonString);


下面应该让您了解当您要手动创建JSON对象时它是如何工作的。

JSONObject mainObject = new JSONObject(); // Main Object.
JSONArray categoryArray; // Category Array.
JSONObject categoryObject; // Category Object.
JSONArray readingsMainArray; // An array of arrays.
JSONArray readingsChildArray; // A child array.
JSONObject readingsObject; // A readings entry.

// Create arrays.
readingsMainArray = new JSONArray();
readingsChildArray = new JSONArray();

// Create JSONObject.
readingsObject = new JSONObject();

// Put values.
readingsObject.put("Name":"SYS");
readingsObject.put("Type":"INT");
readingsObject.put("Value":"200");

// Add to the child array.
readingsChildArray.put(readingsObject);

// Repeat 3 times for the other values.

// Now add the readings child array to the main array.
readingsMainArray.put(readingsChildArray);

// Now the category JSONObject.
categoryObject = new JSONObject();

// Put values.
categoryObject.put("Category","BP);
categoryObject.put("CollectionTime","2015-12-28T09:09:22-05:00");
categoryObject.put("DeviceInfo",null);
categoryObject.put("Readings", readingsMainArray);

// Put the category object into the category array.
categoryArray = new JSONArray();
categoryArray.put(categoryObject);

// Repeat this process for the "second" category array.

// Add category array to the main object.
mainObject.put("PeripheralList",categoryArray);


让我知道是否有帮助。

关于java - Android-JSON-如何使用JSONObject和JSONArray类型创建JSON对象和JSON数组以匹配此格式?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34753046/

10-09 13:16