c# - JSON has the same identifier for a property and a field, how can I get around this?
问题描述
The following is a snippet of some JSON that I am receiving from a 3rd party API.
{"for":
{
"total":
{"home":0,"away":0,"total":0},
"average":
{"home":"0.0","away":"0.0","total":"0.0"},
"total":1,
"average":"0.5"
}
}
The classes I have for deserialisation:
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; }
}
The error:
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
Additional information: Unexpected character encountered while parsing value: {. Path 'response[0].for.total', line 1, position 1047.
The error when changing the case of a property and using [JsonProperty(PropertyName = "total")]
Additional information: A member with the name 'total' already exists on 'namespace1.For'. Use the JsonPropertyAttribute to specify another name.
解决方案
Jason 允许重复键,但只会假定最后一个键。C# 不允许任何双重属性,所以我看到的最简单的方法是重命名 json 键。而且由于没有人手动创建 Json,但计算机将始终创建相同的模式,这是最简单的方法,只是使用字符串函数(或者您可以尝试正则表达式)。
尝试这个
json=json.Replace("total\":{", "totalDetails\":{").Replace("average\":{","averageDetails\":{");
var jsonDeserialized = JsonConvert.DeserializeObject<Root>(json);
输出
{"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; }
}
推荐阅读
- visual-studio-2017 - 使用 pip 安装 Twisted for Python:错误:Microsoft Visual Studio 失败,退出状态为 2
- jquery - jQuery - 仅在元素加载后运行函数
- jags - 将 jagam 代码插入 runjags (JAGS) 模型
- javascript - 无法在模式对话框中显示表单
- git - 如何列出带有原始提交日期的 git 标签
- javascript - 如何将ajax post数据传递给nodejs服务器?
- java - 如何识别 Java 程序中对外部类和方法的声明和引用?
- c# - 尝试使用 GDAL/OGR 打开 shapefile 时,“gdalconst_wrap”dll 丢失或无法读取
- python - 序列化字段时如何获取字符串片段(Django / DRF)
- spring - 在初始化整个上下文或执行服务器启动后,有什么方法可以初始化 spring bean?