2016-01-12 37 views
0

如何創建JSON對象& JSON數組使用JSONObject匹配此格式& JSONArray類型?Android - JSON - 如何創建JSON對象和JSON數組以匹配使用JSONObject和JSONArray類型的此格式?

{"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"}] 
     ]} 
]} 

任何幫助,將不勝感激。謝謝。

回答

1

您應該能夠將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); 

讓我知道這是否有幫助。

相關問題