[英]How can I get value from json property that has numbers in key name(dynamic object)?
[英]JSON has the same identifier for a property and a field, how can I get around this?
以下是我從第三方 API 收到的一些 JSON 的片段。
{"for":
{
"total":
{"home":0,"away":0,"total":0},
"average":
{"home":"0.0","away":"0.0","total":"0.0"},
"total":1,
"average":"0.5"
}
}
我有反序列化的類:
public class For {
public int total { get; set; }
public string average { get; set; }
public Total total { get; set; }
public Average average { get; set; }
public Minute minute { get; set; }
public int home { get; set; }
public int away { get; set; }
}
public class Total {
public int home { get; set; }
public int away { get; set; }
public int total { get; set; }
}
public class Average {
public string home { get; set; }
public string away { get; set; }
public string total { get; set; }
}
錯誤:
Newtonsoft.Json.dll 中發生類型為“Newtonsoft.Json.JsonReaderException”的未處理異常
附加信息:解析值時遇到意外字符:{。 路徑 'response[0].for.total',第 1 行,position 1047。
更改屬性大小寫並使用[JsonProperty(PropertyName = "total")]
時的錯誤
附加信息:名稱為“total”的成員已存在於“namespace1.For”上。 使用 JsonPropertyAttribute 指定另一個名稱。
Jason 容忍重復的密鑰,但只會假定最后一個。 C# 不允許任何雙重屬性,所以我看到的最簡單的方法是重命名 json 鍵。 由於沒有人手動創建 Json,但計算機將始終創建相同的模式,最簡單的方法是使用字符串函數(或者您可以嘗試使用正則表達式)。
嘗試這個
json=json.Replace("total\":{", "totalDetails\":{").Replace("average\":{","averageDetails\":{");
var jsonDeserialized = JsonConvert.DeserializeObject<Root>(json);
output
{"for":{"totalDetails":{"home":0,"away":0,"total":0},"averageDetails":{"home":"0.0","away":"0.0","total":"0.0"},"total":1,"average":"0.5"}}
類
public class Root
{
public For @for { get; set; }
}
public class TotalDetail
{
public int home { get; set; }
public int away { get; set; }
public int total { get; set; }
}
public class AverageDetail
{
public string home { get; set; }
public string away { get; set; }
public string total { get; set; }
}
public class For
{
public TotalDetail totalDetails { get; set; }
public AverageDetail averageDetails { get; set; }
public int total { get; set; }
public string average { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.