简体   繁体   English

当成员使用 JsonConvert 反序列化两次时如何引发异常

[英]How to throw an exception when member comes twice on Deserializing with JsonConvert

I have JSON which contains duplicated members:我有 JSON ,其中包含重复的成员:

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

When I deserialize, it is getting the last property.当我反序列化时,它正在获取最后一个属性。 Here is the code:这是代码:

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

But I need to throw an exception when JSON string contains duplicated properties.但是当 JSON 字符串包含重复的属性时,我需要抛出异常。 How can I do that?我怎样才能做到这一点?

You can use JsonTextReader from Newtonsoft.Json to get all tokens which are of PropertyName and then probably use LINQ GroupBy() like您可以使用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);
    }
}

Now use GroupBy() on the list to see duplicates现在在列表中使用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");
}

You need to added DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error in your JsonLoadSettings .您需要在JsonLoadSettings添加DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error

You can dig in details following this answer .您可以在this answer之后详细了解。

There is also a thread from Newtonsoft.json that cover this topic.还有一个来自 Newtonsoft.json 的主题涵盖了这个主题。

Here you go:这里是 go:

            public object DeserializeObject(string json)
            {
                using (var stringReader = new StringReader(json))
                using (var jsonReader = new JsonTextReader(stringReader))
                {

                    return JToken.ReadFrom(jsonReader, 
                        new JsonLoadSettings{ DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error })
                        .ToObject<object>();
                }
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么反序列化到字典时JsonConvert会引发异常 - Why is JsonConvert throwing exception when deserializing to a dictionary 反序列化为double时,JsonConvert会抛出一个“非有效整数”异常 - JsonConvert throws a 'not a valid integer' exception when deserializing to a double 反序列化双精度类型变量时,JsonConvert引发“无效整数”异常 - JsonConvert throws a 'not a valid integer' exception when deserializing double type variable JsonConvert.DeserializeObject 在反序列化 CouchBase 响应时抛出异常 - JsonConvert.DeserializeObject throws exception when deserializing CouchBase response 将具有十六进制值的JSON反序列化为sbyte属性时,JsonConvert.DeserializeObject引发异常 - JsonConvert.DeserializeObject throws an exception when deserializing JSON with a hex value into an sbyte property JsonSerializer.Deserialize 在反序列化不同的 class 时预计会抛出异常 - JsonSerializer.Deserialize expected to throw exception when deserializing different class 使用 JsonConvert 反序列化 Json 文件时进行调试 - Debugging when deserializing a Json file with JsonConvert 反序列化为数据集时,JsonConvert.DeserializeObject 不起作用 - JsonConvert.DeserializeObject is not working when deserializing to a DataSet 是否有理由两次抛出异常? - Is there a reason to throw an exception twice? 在JsonConvert.DeserializeObject中反序列化对象时出现意外的标记 - Unexpected token when deserializing object in JsonConvert.DeserializeObject
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM