簡體   English   中英

當成員使用 JsonConvert 反序列化兩次時如何引發異常

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

我有 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 字符串包含重復的屬性時,我需要拋出異常。 我怎樣才能做到這一點?

您可以使用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");
}

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

您可以在this answer之后詳細了解。

還有一個來自 Newtonsoft.json 的主題涵蓋了這個主題。

這里是 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM