我正在尝试访问一个名为“ block”的嵌套JSON变量,但似乎无法以任何尝试的方式对其进行访问。这是示例JSON消息和我的代码:
{“ account”:“ xrb_34tsctqcgctm8fhnpat351z4f64rgz8o9y7gwh1dutjf1r7iiwfzruawhatz”,“哈希”:“ E5935C559748444444D09E97D6D13FDB48B51F46A01FA9F6D6”“:\\” xrb_34tsctqcgctm8fhnpat351z4f64rgz8o9y7gwh1dutjf1r7iiwfzruawhatz \ “\ n \ ”以前的\“:\ ”78446816869EEEF4BC735B1A21AB33ED246A10303B87F0CAFD7CCD56406E0456 \“,\ n \ ”代表\“:\ ”xrb_3pczxuorp48td8645bs3m6c3xotxd3idskrenmi65rbrga5zmkemzhwkaznh \“,\ n \ ”平衡\“:\ ”320000000000000000000000000 \“,\ n \”链接\ “:\” 8DE4EE799910E26C5E44CDD345B8C8070E1955284BC407660825B425FBEDBB6B \ “\ n \ ”link_as_account \“:\ ”xrb_35h6xswsk694fjh6bmgmapwei3rg57ckiky61xm1ibfn6qxyugud9eo1fauk \“,\ n \ ”签名\“:\ ”E4AF5BBDF583509DF3147004AB61FEC04F9007AC23A46A2E2E5BE4B65D0788F45F89EEC7B62D0F42144A9F5EA090EF3F58262070F07C59F1AD752B5CC3BF9D04 \“,\ n \ ”工作\“:\” a56cb9e8d2539f73 \ “ \ n} \ n”,“金额”:“ 1`
struct IncomingBlock: Decodable {
var account: String
var hash: String
struct Block: Decodable {
var type: String
var previous: String
var link: String
var link_as_account: String
var representative: String
var account: String
var balance: String
var work: String
var signature: String
}
var block: Block
}
// in another file
guard let data = msg.data(using: .utf8) else { return }
guard let incomingBlock = try?JSONDecoder().decode(IncomingBlock.self, from: data) else { return }
答案 0 :(得分:1)
基本上,要访问嵌套的JSON
变量block
,我必须解码初始的JSON
消息
do{
guard let data = inital_msg.data(using: .utf8) else { return }
let incomingBlock = try JSONDecoder().decode(IncomingBlock.self, from: data)
catch ...{}
,并将block
的值强制转换为模型中的String。
struct IncomingBlock: Decodable {
var account: String
var hash: String
var block: String
}
之后,我又像这样对初始消息block
字段进行了解码
//第二个JSON
let json = incomingBlock.block.data(using: .utf8)!
最后使用分离的块模型:
struct BlockMeta: Decodable {
var type: String
var previous: String
var link: String
var link_as_account: String
var representative: String
var account: String
var balance: String
var work: String
var signature: String
}
我可以访问这些字段
let block = try JSONDecoder().decode(BlockMeta.self, from: json)
block.balance //returns "320000000000000000000000000"