1

How do I ignore duplicate fields?

For example I have this raw json { "Value": 3, "Name": "Test", "value": "irrelevant" }

I would like to ignore value because my target type has public int Value { get; set; }

We have this kind of issue on most of the data from the client side views. In asp.net core, how do we instruct the json serializer to use the property that matches the type in the target?

Cheers,

Marc LaFleur
  • 31,987
  • 4
  • 37
  • 63
herme 0
  • 912
  • 1
  • 9
  • 23
  • Your example json seems to be invalid (value is not quoted?)... Do you have multiple members just differing in case? – Thejaka Maldeniya Mar 30 '18 at 15:09
  • Fixed the typo and added the quotes. Yes, I have multiple members just differing in case. – herme 0 Mar 30 '18 at 15:13
  • If you are using Json.NET, perhaps you can add [JsonIgnore] attribute to the fields you wish to exclude from serialization... – Thejaka Maldeniya Mar 30 '18 at 15:22
  • [JsonIgnore] is applied on the target clr type. In this case I don't want to ignore it, I want to deserialize it but as an integer. So if a literal string is encountered it should ignore it when the conversion to integer fails. – herme 0 Mar 30 '18 at 15:33
  • Well I guess the issue here is that the json is invalid(an error occured during deserialization). And it seems like the general consensus is to not sugarcoat the issue and invalidate the request instead of moving on with a probably broken data. – herme 0 Mar 30 '18 at 16:02
  • looks like you cannot do this with current version of Json.NET: [issues/815: Provide a way to do case-sensitive property deserialization](https://github.com/JamesNK/Newtonsoft.Json/issues/815) – Set Mar 30 '18 at 17:53

1 Answers1

0

Unfortunately, this isn't possible.

Assuming this JSON:

{ 
   "Value": 3, 
   "Name": "Test", 
   "value": "irrelevant" 
}

And this class:

public class MyClass
{
    public string Value { get; set; }  
    public string Name { get; set; }         
}

JSON.NET will deserialize as follows:

  1. Value = 3
  2. Name = "Test"
  3. Value = "irrelevant"

The deserializer doesn't have a "state" so it doesn't care if Value was previously deserialized; it simply assigns the properties as it goes.

The reason you're getting an error is that your class defines Value as an int. This results in the deserializer executing:

  1. Value = 3
  2. Name = "Test"
  3. Value = "irrelevant" <--- throw exception because int can't be set to a string value.
Marc LaFleur
  • 31,987
  • 4
  • 37
  • 63
  • Do you know if we can change this behavior so that the deserialziation proceeds even if an exception was thrown at any step? – herme 0 Mar 30 '18 at 20:47