首页 > 解决方案 > C# Json 如何使用可能是任何类型的 int 的键来反序列化某些东西

问题描述

我正在开发一个 Xamarin 应用程序,我使用 Newtonsoft for Json。但是我在处理一些我回来的数据时遇到了麻烦。

{
"ok": true,
"payment-methods": [
     {
     "id": "39sahf92ka9s02",
         "type": "ideal",
            "options": {
                "issuers": {
                    99: "Test Issuer"
                }
            }
        }
    ],
}

我不知道如何到达 Test Issuer,因为 Key 值可以是任何整数。

Dictionary 使用起来很有意义,但随后出现以下异常:“System.NullReferenceException: Object reference not set to an instance of an object.json”

我有以下模型:

[JsonObject(MemberSerialization.OptIn)]
public class PaymentOptions
{
    [JsonProperty("ok")]
    public Boolean OK { get; set; }
    [JsonProperty("payment-methods")]
    public List<PaymentMethods> PaymentMethods { get; set; }
}
public class PaymentMethods
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("type")]
    public string Type { get; set; }
    [JsonProperty("options")]
    public Options Options { get; set; }
}
public class Options
{
    [JsonProperty("issuers")]
    public IDictionary<int, string> Issuers { get; set; }
}

我通过以下方式反序列化 Json:

var deserializedGetPaymentOptions = JsonConvert.DeserializeObject<Models.PaymentMethods>(await responseGetPaymentOptions.Content.ReadAsStringAsync());

之后,我尝试在 foreach 循环中使用它来阅读它:

foreach (KeyValuePair<int, string> issuerFromDict in deserializedGetPaymentOptions.Options.Issuers)

标签: c#xamarinjson.net

解决方案


您是否尝试过在 json 表示中使用 99 作为字符串?

...
"issuers": {
    "99": "Test Issuer"
}
...

您应该让 newtonsoft 处理到 int 的转换。


推荐阅读