JSON 对于 属性 和字段具有相同的标识符,我该如何解决这个问题?

JSON has the same identifier for a property and a field, how can I get around this?

以下是我从第三方 API.JSON 收到的一些 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; }
    }

错误:

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.

改变属性的大小写并使用[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; }
}