簡體   English   中英

在Swift 3中從JSON數據解析JSON數組

[英]Parsing JSON array from JSON data in Swift 3

我在解析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
}
}

這是當infoType == 4Body外觀: {"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;
    }

    )

假設您的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"])              
    }
}

如果我做錯了或不符合您的要求,或者您沒聽懂,請詢問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM