我想将JSON中的值分配给变量,问题是Swift认为我正在传递整个数组,而不仅仅是将code
的JSON值传递给变量。
我具有以下结构和JSON解码功能:
private func JSONFunction() {
guard let url = URL(string: "https://example.com/example/example"),
let nameValue = stringValue.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "name=\(nameValue)".data(using: .utf8)
URLSession.shared.dataTask(with: request) { data, _, error in
guard let data = data else { return }
do {
let myData = try JSONDecoder().decode(codeStruct.self, from:data)
DispatchQueue.main.async {
codeNum = myData.code
print(codeNum)
}
}
catch {
print(error)
}
}.resume()
}
以下是用于解码JSON的结构:
struct codeStruct: Codable {
let code: String
let line: String
let person: String
let maker: String
}
收到错误:
typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath:[],debugDescription: “打算解码字典,但找到一个数组 相反。”,underlyingError:nil))
答案 0 :(得分:1)
如果不用猜测json,我想说的是,传入的JSON实际上是一个codeStruct对象数组,为此您应将行更改为
Do Until IsEmpty(Sheets("Orig Data").Range("A" & DataRow + 1)) = True
Select Case Range("K" & DataRow).Value
Case "1"
Sheets("Output").Range("AI" & OutputRow) = "Y"
Case "2"
Sheets("Output").Range("AJ" & OutputRow) = "Y"
Case "3"
Sheets("Output").Range("AK" & OutputRow) = "Y"
End Select
If Sheets("Orig Data").Range("Y" & DataRow) <> Sheets("Orig Data").Range("Y" & DataRow + 1) Then
OutputRow = OutputRow + 1
DataRow = DataRow + 1
Worksheets("Orig Data").Range("A" & DataRow & ":AH" & DataRow).Copy Worksheets("Output") _
.Range("A" & OutputRow & ":AH" & OutputRow)
Else
DataRow = DataRow + 1
If IsEmpty(Sheets("Orig Data").Range("A" & DataRow + 1)) = True Then
MsgBox "Done"
Exit Sub
End If
End If
Loop