如何创建一个结构来匹配这个 Json [英] How to create a struct to match this Json

查看:20
本文介绍了如何创建一个结构来匹配这个 Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从 api 中获取一个随机用户,我创建了一个名为 result 的结构来匹配来自 api 的 json.这是我想出的,但我确定这不是正确的方法!当我运行它时,我得到 [] 结果,所以我想知道如何更改此代码以匹配 json

I am trying to fetch a random user from an api and I created a struct called result to match the json from the api. This is what I came up with but I am sure this is not the right way to do it! When I run this I get [] as a result so I want to know how I can change this code in order to match the json

@State var 结果:结果?

@State var results : result?

struct  result : Codable {
    var results : [user]

    struct user : Codable{
        
        var gender : String
        var name : name
        var location : location
        var email:String
        
        
        
        
        struct name : Codable{
            var  title : String
            var first : String
            var last : String
        }
        
        struct location : Codable {
            let street : street
            let city : String
            let state : String
            let country : String
            let postcode : Int
            
            struct street :Codable {
                var number : String
                var name : String
            }
        }
        
        struct login : Codable {
            var uuid : String
            var username : String
            var password : String
            
        }
        
    }

}

这是 Json 的样子

This is how the Json looks

{
  "results": [
    {
      "gender": "male",
      "name": {
        "title": "mr",
        "first": "brad",
        "last": "gibson"
      },
      "location": {
        "street": "9278 new road",
        "city": "kilcoole",
        "state": "waterford",
        "postcode": "93027",
        "coordinates": {
          "latitude": "20.9267",
          "longitude": "-7.9310"
        },
        "timezone": {
          "offset": "-3:30",
          "description": "Newfoundland"
        }
      },
      "email": "brad.gibson@example.com",
      "login": {
        "uuid": "155e77ee-ba6d-486f-95ce-0e0c0fb4b919",
        "username": "silverswan131",
        "password": "firewall",
        "salt": "TQA1Gz7x",
        "md5": "dc523cb313b63dfe5be2140b0c05b3bc",
        "sha1": "7a4aa07d1bedcc6bcf4b7f8856643492c191540d",
        "sha256": "74364e96174afa7d17ee52dd2c9c7a4651fe1254f471a78bda0190135dcd3480"
      },
      "dob": {
        "date": "1993-07-20T09:44:18.674Z",
        "age": 26
      },
      "registered": {
        "date": "2002-05-21T10:59:49.966Z",
        "age": 17
      },
      "phone": "011-962-7516",
      "cell": "081-454-0666",
      "id": {
        "name": "PPS",
        "value": "0390511T"
      },
      "picture": {
        "large": "https://randomuser.me/api/portraits/men/75.jpg",
        "medium": "https://randomuser.me/api/portraits/med/men/75.jpg",
        "thumbnail": "https://randomuser.me/api/portraits/thumb/men/75.jpg"
      },
      "nat": "IE"
    }
  ],
  "info": {
    "seed": "fea8be3e64777240",
    "results": 1,
    "page": 1,
    "version": "1.3"
  }
}

推荐答案

您想学习如何自己完成此操作,但网络上有一些工具可以轻松帮助您创建 struct来自 JSON.这个非常好.

You want to learn how to do this on your own but there are tools on the web that can easily help you create a struct from a JSON. This is a really good one.

你很接近所以一定要剖析代码并注意差异

You were close so make sure you dissect the code and notice the differences

import SwiftUI
class ResultsViewModel: ObservableObject{
    let json = """
{
      "results": [
        {
          "gender": "male",
          "name": {
            "title": "mr",
            "first": "brad",
            "last": "gibson"
          },
          "location": {
            "street": "9278 new road",
            "city": "kilcoole",
            "state": "waterford",
            "postcode": "93027",
            "coordinates": {
              "latitude": "20.9267",
              "longitude": "-7.9310"
            },
            "timezone": {
              "offset": "-3:30",
              "description": "Newfoundland"
            }
          },
          "email": "brad.gibson@example.com",
          "login": {
            "uuid": "155e77ee-ba6d-486f-95ce-0e0c0fb4b919",
            "username": "silverswan131",
            "password": "firewall",
            "salt": "TQA1Gz7x",
            "md5": "dc523cb313b63dfe5be2140b0c05b3bc",
            "sha1": "7a4aa07d1bedcc6bcf4b7f8856643492c191540d",
            "sha256": "74364e96174afa7d17ee52dd2c9c7a4651fe1254f471a78bda0190135dcd3480"
          },
          "dob": {
            "date": "1993-07-20T09:44:18.674Z",
            "age": 26
          },
          "registered": {
            "date": "2002-05-21T10:59:49.966Z",
            "age": 17
          },
          "phone": "011-962-7516",
          "cell": "081-454-0666",
          "id": {
            "name": "PPS",
            "value": "0390511T"
          },
          "picture": {
            "large": "https://randomuser.me/api/portraits/men/75.jpg",
            "medium": "https://randomuser.me/api/portraits/med/men/75.jpg",
            "thumbnail": "https://randomuser.me/api/portraits/thumb/men/75.jpg"
          },
          "nat": "IE"
        }
      ],
      "info": {
        "seed": "fea8be3e64777240",
        "results": 1,
        "page": 1,
        "version": "1.3"
      }
    }
""".data(using: .utf8)
    
    var result: JSONObject?  {
        var decoded: JSONObject? = nil
        do{
            decoded =  try JSONDecoder().decode(JSONObject.self, from: json!)
        }catch{
            print(error)
        }
        return decoded
    }
}

struct ResultsView: View {
    @StateObject var vm: ResultsViewModel = ResultsViewModel()
    var body: some View {
        if vm.result == nil || vm.result?.results.first == nil{
            Text("nil")
        }else{
            VStack{
                Text(vm.result!.results.first!.name.first)
                Text(vm.result!.results.first!.name.last)
            }
        }
    }
}
// MARK: - JSONObject
struct JSONObject: Codable {
    let results: [Result]
    let info: Info
}

// MARK: - Info
struct Info: Codable {
    let seed: String
    let results, page: Int
    let version: String
}

// MARK: - Result
struct Result: Codable {
    let gender: String
    let name: Name
    let location: Location
    let email: String
    let login: Login
    let dob, registered: Dob
    let phone, cell: String
    let id: ID
    let picture: Picture
    let nat: String
}

// MARK: - Dob
struct Dob: Codable {
    let date: String
    let age: Int
}

// MARK: - ID
struct ID: Codable {
    let name, value: String
}

// MARK: - Location
struct Location: Codable {
    let street, city, state, postcode: String
    let coordinates: Coordinates
    let timezone: Timezone
}

// MARK: - Coordinates
struct Coordinates: Codable {
    let latitude, longitude: String
}

// MARK: - Timezone
struct Timezone: Codable {
    let offset, timezoneDescription: String
    
    enum CodingKeys: String, CodingKey {
        case offset
        case timezoneDescription = "description"
    }
}

// MARK: - Login
struct Login: Codable {
    let uuid, username, password, salt: String
    let md5, sha1, sha256: String
}

// MARK: - Name
struct Name: Codable {
    let title, first, last: String
}

// MARK: - Picture
struct Picture: Codable {
    let large, medium, thumbnail: String
}

这篇关于如何创建一个结构来匹配这个 Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆