1

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?

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
Dilshod K
  • 2,924
  • 1
  • 13
  • 46
  • Use a custom Converter using the `JsonConverter`. Refer https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to – Sathish Guru V May 16 '20 at 08:22
  • This might help: https://stackoverflow.com/questions/20714160/how-to-deserialize-json-with-duplicate-property-names-in-the-same-object – Willy David Jr May 16 '20 at 08:32
  • Does this answer your question? [How to deserialize JSON with duplicate property names in the same object](https://stackoverflow.com/questions/20714160/how-to-deserialize-json-with-duplicate-property-names-in-the-same-object) – Pavel Anikhouski May 16 '20 at 08:47
  • @PavelAnikhouski this does not answer the question. – Maytham Fahmi May 16 '20 at 09:58
  • @maytham-ɯɐɥʇʎɐɯ Actully, it seems to be an exact duplicate, as well as many others questions on this site, which can be found by googling within few minutes (like [Json.NET (Newtonsoft.Json) - Two 'properties' with same name?](https://stackoverflow.com/questions/3877526/json-net-newtonsoft-json-two-properties-with-same-name). One of the answers below shows the same approach with answers in duplicates – Pavel Anikhouski May 16 '20 at 10:07
  • As I understand OP need to throw exception. – Maytham Fahmi May 16 '20 at 10:27

3 Answers3

2

You can use JsonTextReader from Newtonsoft.Json to get all tokens which are of PropertyName and then probably use LINQ GroupBy() like

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

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");
}
Rahul
  • 76,197
  • 13
  • 71
  • 125
2

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.

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
0

JsonConvert.DeserializeObject had that functionality in a older version but they removed it. To provide an alternative they added a new option to the JsonLoadSettings - DuplicatePropertyNameHandling - that allows you to set up the desired behaviour.

Here you 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>();
                }
            }
  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Jul 28 '22 at 01:30