2017-07-06 29 views
-1

我试图分析在斯威夫特API响应的进出口遇到了麻烦嵌套对象和数组的响应斯威夫特3解析API响应麻烦

这里是我的样品JSON

{ 
    "Id": "10", 
    "Name": "PV Prediction By Site", 
    "Description": "", 
    "Permalink": "", 
    "Source_format": "JSON", 
    "Internal_function_name": "get-meteo-by-site", 
    "Additional_parameters": "Prediction", 
    "Sites": null, 
    "Data": [ 
    { 
     "UTCDateString": "2017-05-01T20:10:33Z", 
     "Value": [ 
     { 
      "metadata": { 
      "name": "Beck_Hill", 
      "latitude": 46.26, 
      "longitude": -112.44, 
      "height": 1926, 
      "timezone_abbrevation": "MDT", 
      "utc_timeoffset": -6, 
      "modelrun_utc": "2017-05-01 12:00", 
      "modelrun_updatetime_utc": "2017-05-01 16:41", 
      "kwp": 40.26, 
      "slope": 30, 
      "facing": 180, 
      "tracking": 0 
      }, 
      "units": { 
      "time": "YYYY-MM-DD hh:mm", 
      "pvpower": "kW", 
      "snowcover": "mm", 
      "iam": "percent", 
      "temperature": "C" 
      }, 
      "data_xmin": { 
      "time": [ 
       "2017-05-01 07:00", 
       "2017-05-01 07:15", 
       "2017-05-01 07:30", 
       "2017-05-01 07:45", 
       "2017-05-01 08:00", 
       "2017-05-01 08:15", 
       "2017-05-01 08:30" 
      ], 
      "pvpower_instant": [ 
       40.26, 
       40.26, 
       40.26, 
       40.26, 
       40.26 
      ] 
      } 
     } 
     ] 
    } 
    ] 
} 

而且这里是我的一些解析代码,我可以得到的第一个对象,在“数据”阵列,但是当我试图让第一对象的值字符串时,它未能在AnyObject转换为别的

//get a Dictionary of sites 
     sitesDictionary = try JSONSerialization.jsonObject(with: decodedData, options: .allowFragments) as? [[String:AnyObject]] 

     CoreDataStack.sharedInstance.persistentContainer.performBackgroundTask({ (context) in 
      //loop thorugh all site and create SiteMO objects from them 
      for site in (sitesDictionary?.enumerated())! { 
       //SiteMO 
       let siteMO = SiteMO.siteInfo(siteInfo: site.element, inManagedObjectContext: context)! 
       let siteFeedsDictionary = site.element["Feeds"] as! [[String:AnyObject]] 

       //loop through every feed object and create FeedMO objects from them 
       for feed in siteFeedsDictionary.enumerated() { 
        //FeedMO 
        let feedMO = FeedMO.feedInfo(feedInfo: feed.element, site: siteMO, inManagedObjectContext: context)! 

        //what type of data is in the feed? 
        switch feedMO.additionalParameters! { 
        case "Weather": 
         //its a feed with a Weather object 
         print("There should be a WeatherMO created Here") 

        case "Prediction": 
         //its a feed with a Prediction object 
         let dataArray = feed.element["Data"] as? [[String:AnyObject]] 

我需要一些数据出 “元数据” “单元” 和 “data_xmin” 对象

+2

“值“是一个数组,你试图将它解析为一个字典 – dan

+0

是的,但是当我这样做时让value = feedDataDictionary [”Value“] ?. firstObject as? [字符串:AnyObject] –

+0

当我使用上述 –

回答

0

对于元数据

结果[“数据”] [0] [“值”] [0]

+0

[“数据”] [0]是一个任何?并没有会员“价值” –