-1

just a quick question does anyone know what happens if i would have a JSON string that lets say has the attributes: name, age, gender. and i try to deserialize that to a User class that looks like:

public class User{
int age;
string name;
}

So obviously it doesn't have the gender in it. I'm using the JavaScriptSerializer.deserializeObject function to do it. does anyone know whether it would just skip it as if the json string didnt have the gender in it because it cant find the variable or would it throw an error?

Valhalla
  • 1
  • 3
  • 2
    I believe something like JSON.Net will handle this situation pretty gracefully. Maybe you could take a look at it, too? – Matt Thomas Mar 09 '17 at 14:28
  • One thing you can try is deserializing it to an object or dynamic, and then use reflection to only set properties that exist on both. I normally use the Newtonsoft JSON libraries personally. – Eric Lizotte Mar 09 '17 at 14:47
  • 1
    Possible duplicate of [Deserialize JSON into C# dynamic object?](http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object) – user1859022 Mar 09 '17 at 15:07

2 Answers2

1

It will thrown an ArgumentException.

The documentation says that one of the reasons for throwing an exception is:

input includes member definitions that are not available on the target type.

where input is your JSON text.

Andrei V
  • 7,306
  • 6
  • 44
  • 64
0

By default it will ignore properties that aren't part of the target type.

You can change this behaviour with an overload which allows you to supply an instance of JsonSerializerSettings used for the deserialization: documentation for DeserializeObject

try
{
    JsonConvert.DeserializeObject<Account>(json, new JsonSerializerSettings
    {
        MissingMemberHandling = MissingMemberHandling.Error
    });
}
catch (JsonSerializationException ex)
{
    Console.WriteLine(ex.Message);
    // Could not find member 'DeletedDate' on object of type 'Account'. Path 'DeletedDate', line 4, position 23.
}

Example from documentation for MissingMemberHandling type

Kevin Sijbers
  • 814
  • 7
  • 19