首页 > 解决方案 > 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.

标签: c#json.net

解决方案


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; }
}

推荐阅读