【问题标题】:How to throw an exception when member comes twice on Deserializing with JsonConvert当成员使用 JsonConvert 反序列化两次时如何抛出异常
【发布时间】:2020-09-02 03:02:58
【问题描述】:

我有包含重复成员的 JSON:

[
  {
    "MyProperty": "MyProperty1",
    "MyProperty": "MyWrongProperty1",
    "MyProperty2": "MyProperty12",
    "MyProperty2": "MyWrongProperty2"
  },
  {
    "MyProperty": "MyProperty21",
    "MyProperty2": "MyProperty22"
  }
]

当我反序列化时,它正在获取最后一个属性。代码如下:

var myJson = File.ReadAllText("1.txt");
List<MyClass> myClasses = JsonConvert.DeserializeObject<List<MyClass>>(myJson);

但是当 JSON 字符串包含重复的属性时,我需要抛出异常。我怎样才能做到这一点?

【问题讨论】:

标签: c# json json.net deserialization jsonconvert


【解决方案1】:

您需要在JsonLoadSettings 中添加DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error

你可以关注这个answer详细挖掘。

还有一个来自 Newtonsoft.json 的主题,涵盖 this 主题。

【讨论】:

    【解决方案2】:

    您可以使用Newtonsoft.Json 中的JsonTextReader 来获取属于PropertyName 的所有令牌,然后可能使用LINQ GroupBy() 之类的

    string json = "[
      {
        "MyProperty": "MyProperty1",
        "MyProperty": "MyWrongProperty1",
        "MyProperty2": "MyProperty12",
        "MyProperty2": "MyWrongProperty2"
      },
      {
        "MyProperty": "MyProperty21",
        "MyProperty2": "MyProperty22"
      }
    ]";
    
    List<string> props = new List<string>();
    
    JsonTextReader reader = new JsonTextReader(new StringReader(json));
    while (reader.Read())
    {
        if (reader.Value != null && reader.TokenType == "PropertyName")
        {
            props.Add(reader.Value);
        }
    }
    

    现在使用列表中的GroupBy() 来查看重复项

    var data = props.GroupBy(x => x).Select(x => new 
               {
                 PropName = x.Key,
                 Occurence = x.Count()
               }).Where(y => y.Occurence > 1).ToList();
    
    If (data.Any())
    {
      Throw New Exception("Duplicate Property Found");
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多