英文:
Parsing only few of the fields in json
问题
struct SymptomCheckerResult: Codable {
let action: String?
enum CodingKeys: String, CodingKey {
case action = "action"
}
}
let jsonData = Data(messageBody.utf8)
do {
let symptomCheckerResult = try JSONDecoder().decode(SymptomCheckerResult.self, from: jsonData)
print(symptomCheckerResult)
} catch (let error) {
print(error)
}
英文:
I am trying to parse following json:
"{\"action\":\"question-answered\",\"data\":{\"type\":\"agreement\",\"questionType\":{},\"answer\":{}}}"
with following model:
struct SymptomCheckerResult: Codable {
let action: String?
enum CodingKeys: String, CodingKey {
case action = "action"
}
}
I just require value from one key. But my parsing is failing with following error message:
> typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found a string/data instead.", underlyingError: nil))
Following is my parsing code:
let jsonData = Data(messageBody.utf8)
do {
let symptomCheckerResult = try JSONDecoder().decode(SymptomCheckerResult.self, from: jsonData)
print(symptomCheckerResult)
} catch (let error) {
print(error)
}
I could have a very long json but I just need values from 1 key but my parsing is always failing.
It looks very simple but somehow it is not working for me. Can someone please help me point my mistake?
答案1
得分: 1
你已经对JSON进行了字符串化处理:您的JSON是一个JSON字符串,以双引号开头。它不是直接的JSON。
如果我们需要在Swift中声明您的答案,它可能是:
let messageBody = """
"{\\\"action\\\":\\\"question-answered\\\",\\\"data\\\":{\\\"type\\\":\\\"agreement\\\",\\\"questionType\\\":{},\\\"answer\\\":{}}}"
"""
实际上有反斜杠,这不是控制台打印它们的原因,而是由于调试工具。
因此,您需要首先对其进行序列化:
let jsonStr = try JSONDecoder().decoder(String.self, from: jsonData)
let symptomCheckerResult = try JSONDecoder().decode(SymptomCheckerResult.self, from: Data(jsonStr.utf8))
英文:
You have JSON Stringified: Your JSON is a JSON String, it starts with a double quotes. It's not direct JSON.
If we needed to declare your answer in Swift, it could be:
let messageBody = """
"{\\\"action\\\":\\\"question-answered\\\",\\\"data\\\":{\\\"type\\\":\\\"agreement\\\",\\\"questionType\\\":{},\\\"answer\\\":{}}}"
"""
There are actually backslash, it's not the Console that print them because of debugging tools.
So you need to serialize it first:
let jsonStr = try JSONDecoder().decoder(String.self, from: jsonData)
let symptomCheckerResult = try JSONDecoder().decode(SymptomCheckerResult.self, from: Data(jsonStr.utf8)
答案2
得分: -1
尝试使用方便的SwiftyJSON库(至少对我来说是方便的)。它可以让您非常灵活地处理JSON。
在这种情况下,代码将如下所示。
- 从字符串或数据中获取JSON。
- 获取所需字段的类型化值。
如果JSON中没有这样的参数,它将返回nil。
let json = JSON(data: data)
let actionValue = json["action"].string
英文:
Try the SwiftyJSON library, which is convenient (at least for me). It lets you work with JSON quite flexibly.
https://github.com/SwiftyJSON/SwiftyJSON
In this case the code will look like this.
- Get JSON from string or data.
- Get the typed value of the desired field.
If there is no such parameter in JSON it will return nil.
let json = JSON(data: data)
let actionValue = json["action"].string
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论