0

Need to handle duplicate property names in incoming json to Asp.Net Web API. Accordingly such json needs to be rejected in first place.
Below is the input json:

{
"OId":"OId-1",
"OId":"OId-2",
"Addresses":[
              {
                  "Prop1":"PROP-1",
                  "Prop2":"PROP-2",
              },
              {
                  "Prop1":"PROP-1",
                  "Prop2":"PROP-2",
              },
        ],

"Addresses":[
                {
                    "Prop1":"PROP-1",
                    "Prop2":"PROP-2",           
                },
            ],}

C# Object to be desterilized to:

 public class Person
{
    public string OId { get; set; }
    public List<Address> Addresses { get; set; }

}

public class Address
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

Concern: Newtonsoft.Json ignores these duplicate values and deserialises to:

person.OId ="OId-2";Addresses->Count = 3;

Taking the latest property name and value. And in terms of Arrays it combines them to form a single array.In above case 3.

  • Please include the api method signature – bvoleti Aug 26 '16 at 04:37
  • Well, I know it's obvious but it is the API that needs to be fixed in this case. So that it returns in proper format. Besides that I can only think of String operations, to create 2 separate jsons and deserialize both. – uTeisT Aug 26 '16 at 04:50
  • API Signature: public HttpResponseMessage Post(Person person) – Maheshbhushan Kshirsagar Aug 26 '16 at 06:06
  • According to [this answer](https://stackoverflow.com/questions/12806080/json-net-catching-duplicates-and-throwing-an-error/12807438#12807438) you can deserialize to an intermediate `JToken` using `(JToken)JsonConvert.DeserializeObject(json)` and get a duplicate key exception. Then deserialize to your final model using [`ToObject()`](http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JToken_ToObject.htm). – dbc Aug 26 '16 at 06:11

0 Answers0