【问题标题】:Parsing JSON array from JSON data in Swift 3在 Swift 3 中从 JSON 数据解析 JSON 数组
【发布时间】:2018-03-19 15:15:42
【问题描述】:

我无法解析 JSON 数据中的 JSON 数组,因为我收到的 JSON 数组并不总是数组。

数组的键是Body,取决于另一个名为infoType 的参数。 Body 将是一个数组或字符串。 infoType's的值可以是1、2、3或4。当收到infoType == 4时,我们得到Body作为一个数组,当infoType的值等于1、2或3时,我们收到Body 作为普通字符串。

当我收到Body 作为JSON 数组时,我想对其进行解析,当它是普通字符串时,我希望将其保存为普通字符串。

这是我的代码:

import Foundation
import UIKit
var Parsedinfo  = [InfoClass]()
class UserInfo: UIViewController
{
    func parseData()
{
    Parsedinfo = []
    let url : String = "url"
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "GET"
    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
    let task = session.dataTask(with: request) { (data, response, error) in
    if let data = data
        {
            do
                {
                let json = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as! NSArray

                for Info in json
                {
                    let info     =    Info as! [String:Any]
                    let Title    =    info["Title"]
                    let InfoID   =    info["InfoID"]
                    let infoType =    info["infoType"]
                    let Body     =    info["Body"]
                    Parsedinfo.append(InfoClass(Title : Title as! String, Body: Body as!String,infoType : infoType as! Int, InfoID : InfoID as! Int))

                }

                }
            catch
            {
                print (error)
            }

   }
   }
      task.resume()
        }
  }
  class InfoClass
{

var Title    :  String
var Body     :  String
var InfoID   :  Int
var infoType :  Int

    init(Title : String,Body:String,infoType : Int, InfoID : Int)
{
    self.Title = Title
    self.Body = Body
    self.InfoID = InfoID
    self.infoType = infoType
}
}

这是BodyinfoType == 4 时的样子: {"lat":000.00000,"lng":000.0000000,"desc":"string"}

infoType is 1, 2, or 3, it's just a normal string like this: "String"`

JSON 结构:

  (
    {
    Body = "{"lat":00.0000,"lng":00.0000,"desc":"string"}";
    InfoID = 139;
    Title = "title";
    UserID = "userid";
    infoType = 4;
   },
   {
        Body = "    {"lat":00.0000,"lng":00.0000,"desc":"string"}";
        InfoID = 340;
        Title = yyy;
        UserID = "userid";
        infoType = 4;
    },
    { 
    Body = "Body";
    InfoID = 340;
    Title = yyy;
    UserID = "userid";
    infoType = 1;
    }

    )

【问题讨论】:

  • 请添加您的 json 结构。
  • 不相关,但 GET 请求不需要 URLRequest。这是默认设置。只需将url 传递给数据任务,dataTask(with: 也接受一个 URL。并且不要在 Swift 中使用NSArray / NSDictionary。你扔掉了强类型信息。使用原生集合类型。
  • @dahiya_boy 你去吧,我用你问的内容编辑了这个问题。

标签: ios arrays json swift3


【解决方案1】:

假设您的 API 结果与您在问题中提到的一样,并且您在 var json 中成功获得了结果。

我在infoType 的基础上解析 json 并将它们的主体列在两个不同的数组中。你有模型类,所以请根据它进行更改。

let json = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as! [Any] 

var arrBodyStr : [String] = []
var arrBodyDict : [Any] = [ ]

for dictData in json{
    if dictData["infoType"] as? Int == 1 {
      arrBodyStr.append(dictData["Body"])
    }
    else{
      arrBodyDict.append(dictData["Body"])              
    }
}

如果我做错了或不符合您的要求或您没有得到,请询问。

【讨论】:

  • 我收到一个错误:“Value of type '[String : Any]' has no member 'append'”在行:“arrBodyDict.append(dictData["Body"])
  • 你不认为它应该看起来像这样for Info in json { let info = Info as! [String:Any] let Title = info["Title"] let InfoID = info["InfoID"] let infoType = info["infoType"] as! Int let unparssedbody = info["Body"] if (infoType == 4){ let bodyJson = try JSONSerialization.jsonObject(with: unparssedbody, options: .mutableLeaves) as! NSArray for BodyInfo in bodyJson! { let Bodyinfo = BodyInfo let lat = Bodyinfo["lat"] let lang = Bodyinfo["lang"] let desc = Bodyinfo["desc"] print(lat,"my lat") }}} 注意我在序列化中遇到错误
  • 错误是:Ambiguous reference to member 'jsonObject(with:options:)'
  • @Duck.P 请现在检查,我已经说过我假设您成功获取 json 值,现在我只是解析它。
  • 你用同样的旧方式解析它,除了你根据 infoType 的值使用不同的声明名称
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多