首页 > 解决方案 > 使用 Newtonsoft.Json,在 iOS 上不反序列化文化不变量?

问题描述

我正在尝试使用以下财务信息读取 json:

{"cost": 0.0, "price": 417.0, "total": 834.0, "doc_id": 2, "status": "Sync", "doc_code": "ORD-5-1", "doc_kind": "O", "username": "02", "createdat": "2019-01-02T17:09:48.478918", "sub_total": 834.0, "tax_value": 0.0, "updatedat": "2019-01-02T17:10:08.00777-05:00", "customer_code": "43915888_37", "delivery_order": 0, "discount_value": 0.0}

但它返回,例如:

"cost": 0.0 //json
cost: 281474976710656 //.NET

如果 iOS 设备的区域设置为西班牙语/哥伦比亚,则会发生这种情况。在美国地区它工作。奇怪的是,它应该适用于不变的文化:

https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonSerializerSettings_Culture.htm

这仅发生在设备上用模拟器就好了

这就是我尝试的方式:

module test.main

open System

open UIKit
open Foundation

let fromJson2T<'T> x = 
    Newtonsoft.Json.JsonConvert.DeserializeObject<'T>(x)

type DocumentRow = {
    doc_id:int32
    doc_kind:string
    doc_code:string
    customer_code:string
    from_code:string option
    username:string
    createdat:DateTime
    updatedat:DateTime
    dueat:DateTime option
    signature:string option
    authorized:string option
    delivery_order:int32
    price:decimal
    cost:decimal
    tax_value:decimal
    discount_value:decimal
    sub_total:decimal
    total:decimal
    status:string
    notes:string option
    syncdata:string option
    version:int32
}

let DOC = """
{"cost": 0.0, "price": 417.0, "total": 834.0, "doc_id": 2, "status": "Sync", "doc_code": "ORD-5-1", "doc_kind": "O", "username": "02", "createdat": "2019-01-02T17:09:48.478918", "sub_total": 834.0, "tax_value": 0.0, "updatedat": "2019-01-02T17:10:08.00777-05:00", "customer_code": "43915888_37", "delivery_order": 0, "discount_value": 0.0}
"""

[<Register ("AppDelegate")>]
type AppDelegate () =
    inherit UIApplicationDelegate ()

    override val Window = null with get, set

    // This method is invoked when the application is ready to run.
    override this.FinishedLaunching (app, options) =
        let row:DocumentRow = fromJson2T(DOC)
        printfn "%A" row
        true

我也尝试

let jsonSettings = JsonSerializerSettings(NullValueHandling = NullValueHandling.Ignore, Culture= System.Globalization.CultureInfo.InvariantCulture)

let fromJson2T<'T> x = 
    Newtonsoft.Json.JsonConvert.DeserializeObject<'T>(x, jsonSettings)

在 OSX、Xamarin.IOS 12.2.1.13、Newtonsoft.Json 12.0.1 上使用 FSHarp.Core 4.5.4。

PD:我更新了代码示例,并且验证很容易重现。我创建了一个空白的 iOS 项目,将代码放入示例中。在模拟器上运行,工作,在设备上,不工作。两者都设置在“(西班牙/美国)”

PD 2:也发生了https://github.com/vsapronov/FSharp.Json 。但是像http://www.fssnip.net/8y/title/JSON-Parser一样手动解析(从浮点数变为十进制数)可以正常工作。

标签: iosjsonxamarinf#json.net

解决方案


推荐阅读