标签: jsondecoder

在 Swift 中将responseJSON更新为responseDecodable

我是 Swift 新手,我正在尝试升级一些旧的 Swift 代码。我收到以下警告:

'responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)' 已弃用:responseJSON 已弃用,并将在 Alamofire 6 中删除。请改用 responseDecodable。

...在下面的代码中:

extension Alamofire.DataRequest {
    func json(_ options: JSONSerialization.ReadingOptions = .allowFragments, successHandler: ((Any?) -> Void)? = nil, failureHandler: ((AFDataResponse<Any>) -> Void)? = nil) -> Self {
        return responseJSON() {
            response in
            if UtilityService.ensureSuccessful(response, failureHandler: { failureHandler?(response) }) {
                successHandler?(response.value)
            }
            NetworkActivityManager.sharedInstance.decrementActivityCount()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我用responseDecodable替换responseJSON,我会收到以下错误:

无法推断通用参数“T”

我需要做什么来更新此代码?

ios swift alamofire jsondecoder

21
推荐指数
2
解决办法
2万
查看次数

`convertFromSnakeCase`策略不适用于Swift中的自定义`CodingKeys`

我尝试使用Swift 4.1的新功能在JSON解码期间将snake-case转换为camelCase.

这是一个例子:

struct StudentInfo: Decodable {
    internal let studentID: String
    internal let name: String
    internal let testScore: String

    private enum CodingKeys: String, CodingKey {
        case studentID = "student_id"
        case name
        case testScore
    }
}

let jsonString = """
{"student_id":"123","name":"Apple Bay Street","test_score":"94608"}
"""

do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let decoded = try decoder.decode(StudentInfo.self, from: Data(jsonString.utf8))
    print(decoded)
} catch {
    print(error)
}
Run Code Online (Sandbox Code Playgroud)

我需要提供自定义,CodingKeys因为convertFromSnakeCase策略无法推断首字母缩略词或首字母缩写词(例如studentID)的大写字母,但我希望convertFromSnakeCase策略仍然适用testScore.但是,解码器抛出错误("没有与键CodingKeys相关的值"),似乎我不能同时使用convertFromSnakeCase策略和自定义 …

ios swift codable jsondecoder

11
推荐指数
1
解决办法
1838
查看次数

在Swift 4中解码没有键的JSON

我正在使用一个返回这个非常可怕的JSON的API:

[
  "A string",
  [
    "A string",
    "A string",
    "A string",
    "A string",
    …
  ]
]
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用JSONDecoder解码嵌套数组,但它没有单个键,我真的不知道从哪里开始......你有什么想法吗?

非常感谢!

arrays json swift swift4 jsondecoder

10
推荐指数
2
解决办法
3960
查看次数

如何在 Django JSONField 中保留键顺序

我很难保留存储在 Django JSONField 中的 JSON 对象中的键顺序。我已尝试按照文档使用自定义编码器和解码器,但 JSON 对象不断重新排序自身:

>>>from models import MyModel
>>>my_dict = {"c": 3, "b": 2, "a": 1}
>>>my_model = MyModel()
>>>my_model.my_field = my_dict
>>>my_model.save()
>>>my_model.refresh_from_db()
>>>my_model.my_field
OrderedDict([('a',1), ('b', 2), ('c', 3)])
Run Code Online (Sandbox Code Playgroud)

我原以为它会回来OrderedDict([('c',3), ('b', 2), ('a', 1)])

这是我到目前为止所尝试过的:

模型.py

import collections
import json
from django.db import models

class OrderedEncoder(json.JSONEncoder):
  def encode(self, o):
    if isinstance(o, collections.OrderedDict):
      encoded_objs = [
        f"{self.encode(k)}: {self.encode(v)}"
        for k, v in o.items()
      ]
      return f"{{{','.join(encoded_objs)}}}"
   else:
     return super().encode(o)

class OrderedDecoder(json.JSONDecoder):
    def __init__(self, …
Run Code Online (Sandbox Code Playgroud)

django django-jsonfield jsonencoder jsondecoder

7
推荐指数
1
解决办法
1411
查看次数

使用Google Translate API和Python3的JSONDecodeError

我已经在Stack Overflow上进行了彻底的搜索,但是找不到此问题的答案。我正在尝试使用适用于Python(3.6.2)的Google Translate API(googletrans 2.2.0),并试图将一组非英语文档翻译成英语。我让Google Translate进行语言检测。这是我的代码:

## newcorpus is a corpus I have created consisting of non-english documents
fileids = newcorpus.fileids
for f in fileids:
    p = newcorpus.raw(f) 
    p = str(p[:15000])
    translated_text = translator.translate(p)
    print(translated_text)
    sleep(10)
Run Code Online (Sandbox Code Playgroud)

我每次都要等待10秒,从而限制了对API的调用。我也一次只喂API 15k个字符,以保持在字符数限制内。

每次运行此代码,都会收到以下错误消息:

## newcorpus is a corpus I have created consisting of non-english documents
fileids = newcorpus.fileids
for f in fileids:
    p = newcorpus.raw(f) 
    p = str(p[:15000])
    translated_text = translator.translate(p)
    print(translated_text)
    sleep(10)
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

python google-translate python-3.x language-translation jsondecoder

6
推荐指数
1
解决办法
2519
查看次数

Swift Codable - 解析可以包含不同数据类型的 JSON 数组

我正在尝试解析一个 JSON 数组,它可以是

{
  "config_data": [
      {
        "name": "illuminate",
        "config_title": "Blink"
      },
      {
        "name": "shoot",
        "config_title": "Fire"
      }
    ]
}
Run Code Online (Sandbox Code Playgroud)

或者它可以是以下类型

{
  "config_data": [
          "illuminate",
          "shoot"
        ]
}
Run Code Online (Sandbox Code Playgroud)

甚至

{
    "config_data": [
              25,
              100
            ]
  }
Run Code Online (Sandbox Code Playgroud)

所以为了使用 JSONDecoder 解析这个,我创建了一个结构如下 -

Struct Model: Codable {
  var config_data: [Any]?

  enum CodingKeys: String, CodingKey {
    case config_data = "config_data"
   }

  init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    config_data = try values.decode([Any].self, forKey: .config_data)
  }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为Any不确认可解码协议。这可能是什么解决方案。数组可以包含任何类型的数据

swift swift4 jsondecoder

6
推荐指数
1
解决办法
1979
查看次数

如何使RealmSwift RealmOptional与Swift Codable兼容?

我面临着一个问题,即我无法使RealmOptional与带有json解码器的快速新Codable功能兼容。

考虑以下Realm对象。

class School: Object, Codable {

    @objc dynamic var id: Int64 = 0

    @objc dynamic var name: String?
    var numberOfStudents = RealmOptional<Int64>()
    var classes = List<Class>()

    enum CodingKeys: String, CodingKey {
       case id
       case name
       case numberOfStudents
       case classes
    }
}

class Class: Object, Codable {
    var name: String?
    var numberOfStudents = RealmOptional<Int64>()
}
Run Code Online (Sandbox Code Playgroud)

在这里我们可以将类声明为Codable,因为我借助此要点为RealmOptinal编写了扩展。但是问题是解码器解码json时。

考虑这个json

let jsonData = """
[
    "id": 1234,
    "name": "Shreesha",
    "numberOfStudents": nil,
    "classes": {
       "name": "Class V",
       "numberOfStudents": 12
    }
]
""".data(using: …
Run Code Online (Sandbox Code Playgroud)

realm swift codable jsondecoder

6
推荐指数
1
解决办法
1441
查看次数

Swift JSONDecoder 无法使用转义字符解码有效的 JSON

在 Playgrounds 中,以下代码会产生错误:

import Foundation

struct Model: Codable {

  let textBody: String

  enum CodingKeys: String, CodingKey {
    case textBody = "TextBody"
  }
}

let json = """
          {
            "TextBody": "First Line\n\nLastLine"
          }
          """.data(using: .utf8)!


let model = try! JSONDecoder().decode(Model.self, from: json)
Run Code Online (Sandbox Code Playgroud)

致命错误:“尝试!” 表达式意外引发错误: Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.",underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Unescaped control字符 27 周围的字符。” UserInfo={NSDebugDescription=字符 27 周围的未转义控制字符。}))):文件 MyPlayground.playground,第 19 行

根据 JSONLint,上面的 JSON 是完全有效的。那么什么给呢?

更新:

我需要一个解决方案来处理从 API 返回的数据。这是我到目前为止想出的东西,但它很糟糕......

if let data = data,
        let …
Run Code Online (Sandbox Code Playgroud)

json swift jsondecoder

6
推荐指数
1
解决办法
2020
查看次数

Flask:orjson 代替 json 模块进行解码

我正在使用烧瓶并且有很多请求。Flask 使用的 json 模块非常慢。我自动可以使用simplejson,但这有点慢,而不是更快。根据文档,我可以定义一个解码器(flask.json_decoder),但是 orjson 没有这个类。我只有功能加载和转储。有人可以解释一下,我如何用orjson交换 json 模块?最后我只想使用负载和转储功能,但我无法连接我的松散端。

python json flask jsondecoder

6
推荐指数
2
解决办法
878
查看次数

UIImage 在编码/解码时不等效

我一直在对我的模型进行一些测试,以确保当我将它们编码为 JSON 然后使用JSONEncoder/Decoder. 然而,我的一项测试失败了,罪魁祸首是UIImage。我已确保在编码/解码过程中没有抛出任何错误。

首先,这是有问题的测试:

func testProfileImageCodable() throws {
    let image = ProfileImage(UIImage(systemName: "applelogo")!)
    try XCTAssertTrue(assertCodable(image))
}
Run Code Online (Sandbox Code Playgroud)

这是我的“可编码性”测试,我确保编码/解码之前和之后类型相等:

func assertCodable<T: Codable & Equatable>(
    _ value: T,
    decoder: JSONDecoder = .init(),
    encoder: JSONEncoder = .init()
) throws -> Bool {
    let encoded = try encoder.encode(value)
    let decoded = try decoder.decode(T.self, from: encoded)
    
    return value == decoded
}
Run Code Online (Sandbox Code Playgroud)

首先,这是我的UIImage工作方式Codable

extension KeyedEncodingContainer {
    mutating func encode(_ value: UIImage, forKey key: Key) throws {
        guard let …
Run Code Online (Sandbox Code Playgroud)

json uiimage swift equatable jsondecoder

6
推荐指数
1
解决办法
730
查看次数