Search code examples
c#jsonjson.netdeserializationjsonconvert

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


I have JSON which contains duplicated members:

[
  {
    "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. How can I do that?


Solution

  • You need to added DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error in your JsonLoadSettings.

    You can dig in details following this answer.

    There is also a thread from Newtonsoft.json that cover this topic.