如何解码 JSON 字典?

huangapple go评论62阅读模式
英文:

How to decode a JSON Dictionary?

问题

我能够解码简单的JSON响应,但随着JSON的嵌套程度增加,我感到困难。

要解码这样的JSON:

[
  {
    "id": "string",
    "username": "string",
    "firstName": "string",
    "lastName": "string",
    "fullName": "string",
    "email": "string",
    "isInActivity": true,
    "activeEventId": "string",
    "initials": "string"
  }
]

我的结构体如下:

struct FriendsStruct: Decodable, Hashable {
    var initials: String
    var username: String
    var firstName: String
    var lastName: String
    var fullName: String
    var email: String
    var isInActivity: Bool
    var activeEventId: String
    var id: String
}

解码的方式如下:

func getFriends(token: String, force: Bool) async throws -> Int {
    var request = EndPoints().getFriendsEndPoint(force: force)
    request.httpMethod = "GET"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    let (data, response) = try await URLSession.shared.data(for: request)
    let httpResponse = response as? HTTPURLResponse
    guard (response as? HTTPURLResponse)?.statusCode == 200 else { return httpResponse?.statusCode ?? 0 }
    let decodedFriends = try JSONDecoder().decode([FriendsStruct].self, from: data)
    self.updateCoreDataFriendsRecords(friendsData: decodedFriends)
    return httpResponse?.statusCode ?? 1000
}

有人能否指导我如何使用相同的方法解码嵌套响应,例如:

{
  "members": [
    {
      "memberId": "string",
      "memberName": "string",
      "memberUsername": "string",
      "memberType": 0,
      "isMyFriend": true,
      "initials": "string"
    }
  ],
  "name": "string",
  "owner": "string",
  "description": "string",
  "groupType": 0,
  "expiryDate": "2023-02-06T20:00:03.834Z",
  "readOnly": true,
  "isDeleted": true,
  "approvalRequired": true,
  "joinWithCode": true,
  "numberOfMembers": 0,
  "groupAssociation": 0,
  "id": "string",
  "etag": "string"
}
英文:

I am able to decode straight forward json responses but as the JSON gets more nested, I'm struggling.

To decode JSON that looks like this:

[
  {
    "id": "string",
    "username": "string",
    "firstName": "string",
    "lastName": "string",
    "fullName": "string",
    "email": "string",
    "isInActivity": true,
    "activeEventId": "string",
    "initials": "string"
  }
]

My struct is:

struct FriendsStruct: Decodable, Hashable {
    var initials: String
    var username: String
    var firstName: String
    var lastName: String
    var fullName: String
    var email: String
    var isInActivity: Bool
    var activeEventId: String
    var id: String
}

And to decode:

func getFriends(token: String, force: Bool) async throws -> Int {
    var request = EndPoints().getFriendsEndPoint(force: force)
    request.httpMethod = "GET"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    let (data, response) = try await URLSession.shared.data(for: request)
    let httpResponse = response as? HTTPURLResponse
    guard (response as? HTTPURLResponse)?.statusCode == 200 else {return httpResponse?.statusCode ?? 0}
    let decodedFriends = try JSONDecoder().decode([FriendsStruct].self, from: data)
    self.updateCoreDataFriendsRecords(friendsData: decodedFriends)
    return httpResponse?.statusCode ?? 1000
}

Can someone advise as to how I might decode with the same approach but with a nested response such as:

{
  "members": [
    {
      "memberId": "string",
      "memberName": "string",
      "memberUsername": "string",
      "memberType": 0,
      "isMyFriend": true,
      "initials": "string"
    }
  ],
  "name": "string",
  "owner": "string",
  "description": "string",
  "groupType": 0,
  "expiryDate": "2023-02-06T20:00:03.834Z",
  "readOnly": true,
  "isDeleted": true,
  "approvalRequired": true,
  "joinWithCode": true,
  "numberOfMembers": 0,
  "groupAssociation": 0,
  "id": "string",
  "etag": "string"
}

答案1

得分: 2

你需要两个结构体:一个是Member结构体,其中包含了与JSON中相同的属性(就像你在简单示例中所做的那样),另一个是外层的结构体,用于包含一个Member数组的属性。例如:

struct Member: Decodable {
   let memberId: String
   let memberName: String
   let memberUsername: String
   let memberType: Int
   let isMyFriend: Bool
   let initials: String
}

struct Group: Decodable {
   let members: [Member]
   let name: String
   let owner: String
   let description: String
   let groupType: Int
   let expiryDate: String
   let readOnly: Bool
   let isDeleted: Bool
   let approvalRequired: Bool
   let joinWithCode: Bool
   let numberOfMembers: Int
   let groupAssociation: Int
   let id: String
   let etag: String
}

这将按照JSON中的数据结构来处理数据。你可能还想进一步使用CodingKeys枚举将一些JSON字段映射到更适合的属性名称,根据需要,将expiryDate使用Date进行解码。

编辑

作为后续步骤,我提到将expiryDate字段解码为Date属性可能是下一步。回答中似乎忽略了这一点,因为它似乎是一个.iso8601日期格式,如果是这样,那么只需相应地设置解码器上的日期解码策略:

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601)
let group = decoder.decode(Group.self, from: json.data(using: .utf8)!)  // 强制解包仅用于简洁性。不建议这样做 ;-)

然而,这不会生效,因为日期字段包含了小数秒,而Swift的解码器仅支持整秒。这使得它更加有趣 如何解码 JSON 字典? 因此,您需要定义一个自定义解码器:

extension DateFormatter {
   static let iso8601WithFractionalSeconds: DateFormatter = {
      let formatter = DateFormatter()
      formatter.locale = Locale(identifier: "en_US_POSIX")
      formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
      formatter.calendar = Calendar(identifier: .iso8601)
      formatter.timeZone = TimeZone(secondsFromGMT: 0)
      return formatter
   }()
}

然后,您可以在解码器内将expiryDate字符串解码为Date。将到期日期字段更改为Date并按照以下方式解码:

struct Group: Decodable {
   //...
   let expiryDate: Date
   //...
}

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601WithFractionalSeconds)
let group = try! decoder.decode(Group.self, from: data)
英文:

You need two structs: a Member struct with properties in the JSON (as you did for the simple example) and an outer level struct for the base data that includes a property which is an array of Member. For example:

struct Member: Decodable {
   let memberId: String
   let memberName: String
   let memberUsername: String
   let memberType: Int
   let isMyFriend: Bool
   let initials: String
}

struct Group: Decodable {
   let members: [Member]
   let name: String
   let owner: String
   let description: String
   let groupType: Int
   let expiryDate: String
   let readOnly: Bool
   let isDeleted: Bool
   let approvalRequired: Bool
   let joinWithCode: Bool
   let numberOfMembers: Int
   let groupAssociation: Int
   let id: String
   let etag: String
   
}

This is treating the data exactly as it is in the JSON. You'd probably want to go further and use a CodingKeys enum to map some of the json fields onto more suitable property names, and maybe, depending on needs, use a Date for the expiry date and decode the date string.

EDIT

As a follow up I mentioned the next step might be decoding the expiryDate field into a Date property. The answer passed over this as it appeared to be an .iso8601 date format, in which case all that is required is to set the date decoding strategy on the decoder accordingly:

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601)
let group = decoder.decode(Group.self, from: json.data(using: .utf8)!)  // force unwrapping for brevity.  Don't ;-)

However this won't work as the date field contains fractional seconds and Swift's decoder only supports whole seconds. This makes it a bit more interesting 如何解码 JSON 字典? as you'll need to define a custom decoder:

extension DateFormatter {
   static let iso8601WithFractionalSeconds: DateFormatter = {
      let formatter = DateFormatter()
      formatter.locale = Locale(identifier: "en_US_POSIX")
      formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
      formatter.calendar = Calendar(identifier: .iso8601)
      formatter.timeZone = TimeZone(secondsFromGMT: 0)
      return formatter
   }()
}

This then lets you decoder the expiryDate string to a Date within the decoder. Change the expiry date field to a Date and decode as below.

struct Group: Decodable {
   //...
   let expiryDate: Date
   //...
}

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601WithFractionalSeconds)
let group = try! decoder.decode(Group.self, from: data)



</details>



huangapple
  • 本文由 发表于 2023年2月7日 04:06:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定