如何解析此JSON并为

时间:2018-03-12 00:17:09

标签: ios json swift

我有一个JSON:

[
{
  "Men": {
    "image": "/url.png",
    "Jeans": [
      {
        "name": "asd",
        "about": "sadvc",
        "image": "/urls.sjd"
      },
      {
        "name": "asd",
        "about": "sadvc",
        "image": "/urls.sjd"
      },
      {
        "name": "asd",
        "about": "sadvc",
        "image": "/urls.sjd"
      }
    ]
  },
  "Women": {
    "image": "/url2.jpeg",
    "All": {}
  }
}
]

如何为"逐步创建结构"进入tableview?

第一视图 - 改变性别 - 女性或男性。 第二 - 改变类型 - 牛仔裤或其他...... 口渴 - 牛仔裤的收集视图(名称,价格和价格)。

现在,我有结构

struct Clothe: Decodable {
    let about: String
    let name: String
    let image: String
}

用于下载JSON的func

var clothes = [Clothe]()
public func downloadJSON(completed: @escaping () -> ()) {
    let url = URL(string: "https...bla-bla/ULRhere.json")

    let request = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 120.0)

    URLSession.shared.dataTask(with: request) { (data, response, error) in
        if error == nil {
            do {
                self.clothes = try JSONDecoder().decode([Clothe].self, from: data!)
                print(self.clothes)
                DispatchQueue.main.async {

                    completed()

                }
            } catch {
                print("JSON Error")
            }
        }

        }.resume()
}

2 个答案:

答案 0 :(得分:1)

enter image description here让json =""" {"男人":{"图片":" / url。 png"," Jeans":[{" name":" asd"," about":" sadvc&#34 ;," image":" /urls.sjd"},{" name":" asd"," about&#34 ;:" sadvc"," image":" /urls.sjd"},{" name":" asd&#34 ;,"关于":" sadvc"," image":" /urls.sjd"}]},"女性&# 34;:{"图像":" /url2.jpeg","所有":{}}}""" .data(使用:.utf8)!

struct Cloth: Decodable {
let Men : MenStruct?
let Women : WomanStruct?}

struct MenStruct: Decodable {
let image: String?
let Jeans: [JeansStruct]?}

struct JeansStruct: Decodable {
let name: String?
let about: String?
let image: String?}

struct WomanStruct: Decodable {
let image: String?}

func executeJson(){
do {
    let cloth = try JSONDecoder().decode(Cloth.self, from: json)
    print(cloth)
}catch {
    print("JSON Error")
}}

executeJson()

Cloth(Men:Optional(__ lldb_expr_88.MenStruct(image:Optional(" /url.png"),Jeans:Optional([__ lldb_expr_88.JeansStruct(name:Optional(" asd&#34) ;),about:可选(" sadvc"),image:可选(" /urls.sjd")),__ lldb_expr_88.JeansStruct(名称:可选(" asd&#34) ;),about:可选(" sadvc"),image:可选(" /urls.sjd")),__ lldb_expr_88.JeansStruct(名称:可选(" asd&#34) ;),about:可选(" sadvc"),image:可选(" /urls.sjd"))]))),女性:可选(__ lldb_expr_88.WomanStruct(图片:可选) (" /url2.jpeg"))))

答案 1 :(得分:0)

这不是一个好的JSON设计。我建议不要使用数据值(“男性”和“女性”或“牛仔裤”与其他类型的服装)作为词典的键。

此外,我建议您的Web服务的响应返回一个字典,其中包含success值(一个表示结果是否成功的布尔值)和一个result键的键(对于回复的内容)。这样,如果出现错误,响应的基本结构将是相同的(但成功的响应将包括result密钥,并且失败可能包括错误消息或错误代码。)

无论如何,我建议像:

{
    "success": true,
    "result": [{
        "name": "Men",
        "image": "men.png",
        "productLine": [{
            "name": "Jeans",
            "image": "jeans.png",
            "products": [{
                    "name": "Slim fit",
                    "about": "Slim Fit Jeans",
                    "image": "slim.png"
                },
                {
                    "name": "Bell Bottom",
                    "about": "Cool bell bottom jeans",
                    "image": "bellbottom.png"
                },
                {
                    "name": "Acid Wash",
                    "about": "Acid wash jeans",
                    "image": "acid.png"
                }
            ]
        }]
    }, {
        "name": "Women",
        "image": "women.jpeg"
    }]
}

然后您可以设置逻辑模型实体:

struct Product: Codable {
    let about: String
    let name: String
    let image: String
}

struct ProductLine: Codable {
    let name: String
    let image: String
    let products: [Product]?
}

struct CustomerCategory: Codable {
    let name: String
    let image: String
    let productLine: [ProductLine]?
}

然后你就像这样处理响应:

func processResponse(_ data: Data) {
    struct ResponseObject: Codable {
        let success: Bool
        let errorCode: Int?
        let result: [CustomerCategory]?
    }

    do {
        let responseObject = try JSONDecoder().decode(ResponseObject.self, from: data)

        guard responseObject.success, let customerCategories = responseObject.result else {
            // handle server error here
            return
        }

        print(customerCategories)
    } catch {
        print(error)
    }
}

这允许您添加新的客户类别(例如儿童)或产品系列(例如牛仔裤以外的东西),而不会影响服务器的基本界面。

other question中,您已经更改了返回数据的性质,但是,我建议您不要将数据属性放在词典的键中。