仅解析JSON中的部分字段。

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

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 = &quot;&quot;&quot;
&quot;{\\\&quot;action\\\&quot;:\\\&quot;question-answered\\\&quot;,\\\&quot;data\\\&quot;:{\\\&quot;type\\\&quot;:\\\&quot;agreement\\\&quot;,\\\&quot;questionType\\\&quot;:{},\\\&quot;answer\\\&quot;:{}}}&quot;
&quot;&quot;&quot;

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。

在这种情况下,代码将如下所示。

  1. 从字符串或数据中获取JSON。
  2. 获取所需字段的类型化值。

如果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.

  1. Get JSON from string or data.
  2. 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[&quot;action&quot;].string

huangapple
  • 本文由 发表于 2023年5月24日 22:04:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324411.html
匿名

发表评论

匿名网友

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

确定