简体   繁体   中英

Parsing JSON array from JSON data in Swift 3

I am having trouble parsing a JSON array inside of JSON data simply because the the JSON array that I receive isn't always an array.

The array's key is Body depending on another parameter called infoType . Body will be an array or a string. infoType's value can be 1, 2, 3, or 4. When the received infoType == 4 , we get Body as an array, and when infoType 's value equals 1, 2, or 3, then we receive Body as a normal string.

When I receive Body as a JSON array, I want to parse it, and when it is a normal string, I want it to be saved as a normal string.

Here is my code:

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
}
}

Here is what Body looks like when infoType == 4 : {"lat":000.00000,"lng":000.0000000,"desc":"string"}

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

JSON structure:

  (
    {
    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;
    }

    )

Assuming your API result is as you mentioned in question and you getting the result successfully in var json .

I am parsing the json on the basis of infoType and listing them body into two different array. You have model class so pls make changes according to that.

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

If I done smthg wrong or doesnt match your requirement or you didn't getting then ask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM