Json 更新结构中的特定值

Json 更新结构中的特定值,json,swift,structure,codable,Json,Swift,Structure,Codable,我似乎不知道如何在Swift 4中更新结构中的特定值。我有这样的结构: struct Export: Decodable { let id: String let name: String let exportType: String } 它充满了我从JSON获得的值。 我用的是JSONDecoder self.Exp = try JSONDecoder().decode([Export].self, from: data!) 现在我收到一个只包含id的新JSON。

我似乎不知道如何在Swift 4中更新结构中的特定值。我有这样的结构:

struct Export: Decodable {
    let id: String
    let name: String
    let exportType: String
}
它充满了我从JSON获得的值。
我用的是JSONDecoder

self.Exp = try JSONDecoder().decode([Export].self, from: data!)
现在我收到一个只包含id的新JSON。
我想用新值更新此结构的id。
JSON发送如下响应:

{
    "id": "70CD044D290945BF82F13C13B183F669"
}
所以,即使我试图将它保存在一个单独的结构中,我也会遇到这个错误

dataCorrupted(Swift.DecodingError.Context(codingPath: [], 
debugDescription: "The given data was not valid JSON.", 
underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 
"JSON text did not start with array or object and option to allow fragments not set."
UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})))

在发布之前,我试图寻找解决方案,但找不到任何解决方案。我对JSON处理和Swift非常陌生

首先,所有JSON的格式都不正确

其次,在您收到正确的JSON后,对于
self.Exp
您将获得数组,但是对于
idDict
您只有一个dictionary对象

因此,将那些属性
保留为可选的
,这些属性不必出现在JSON中。在您的情况下,它将是
name
exportType
作为:

struct Export: Decodable {
    var id: String
    var name: String?
    var exportType: String?
}
self.Exp = try JSONDecoder().decode([Export].self, from: data!)
它可用于
self.Exp
如下:

struct Export: Decodable {
    var id: String
    var name: String?
    var exportType: String?
}
self.Exp = try JSONDecoder().decode([Export].self, from: data!)
对于
idDict
as:

idDict = try JSONDecoder().decode(Export.self, from: data!)

撇开JSON部分不谈,您将无法在
Export
中更新
id
,因为它是一个
let
常量。您可能需要将其更改为
var

如果我理解正确,您将收到一个JSON响应,其中只有一个id。您不会从中创建一个导出结构。您需要单独处理此JSON响应以获取您正在寻找的id。像这样:

import Foundation

let jsonText = """
{"id": "70CD044D290945BF82F13C13B183F669"}
"""

struct IdResponse: Codable {
    let id: String
}

let idResponse: IdResponse = try! JSONDecoder().decode(IdResponse.self, from: jsonText.data(using: .utf8)!)
最后,更新您的
导出
结构:

import Foundation

struct Export: Decodable {
    var id: String
    let name: String
    let exportType: String
}

// Build export object
var export: Export = Export(id: "1", name: "Name", exportType: "TypeA")

// Grab JSON response from somewhere, which contains an updated id
let idResponse: IdResponse = try! JSONDecoder().decode(IdResponse.self, from: jsonText.data(using: .utf8)!)

// Update the object
export.id = idResponse.id

附加说明:
试试看
.data()是危险操作,应妥善处理。
try
语句应该处理抛出的错误以及
.data()的强制展开
应该被检查为
nil
。非常感谢,当我按照你的方式操作时,它会工作!我仍然对JSON感到困惑。。。当我像你一样把它直接放进我的代码中时,一切都很好。但是它不能处理我收到的JSON,它仍然说它不是一个有效的JSON,你知道我如何将我收到的JSON格式化成像你这样的字符串吗?(使用附加的双引号?如果没有双引号,它将无法工作)抱歉,但我们需要更多关于提供响应的服务的详细信息,以及您读取和解码响应的代码。Nvm我发现问题在于我的代码中缺少这一行:
request.setValue(“application/json;charset=utf-8”,forHTTPHeaderField:“内容类型”)
然后我不得不更改Id结构以添加编码键,现在一切正常!再次感谢!!