c# - 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)
解决方案
您是否尝试过在 json 表示中使用 99 作为字符串?
...
"issuers": {
"99": "Test Issuer"
}
...
您应该让 newtonsoft 处理到 int 的转换。
推荐阅读
- python - 演示使用循环和 ifs 来模拟多次滚动单个骰子的结果
- c - CS50 - 为什么返回值 1 + collatz() 而不仅仅是 collatz()?
- sql - 如何根据 SQL Server CASE 语句检索列的单条记录
- python - Python 中的 cut() 函数不像 R 中的 cut() 函数那样工作
- multithreading - Flink 内线程模型设计?
- javascript - 创建数组并将对象推送给它后,对象是 [Object] 而不是实际数据
- python - 使用 @jitclass 装饰器进行类实例化
- logic - 使用等式关系证明定理: ∀[ x ] ∀[ y ] (¬ Eq xy → ¬ Eq (fx) (fy))
- javascript - 来自 svg 对象的角度更改文本值
- react-native - 在效果方法中使用时效果不起作用