Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.net required property not found in json

Tags:

json

c#

json.net

I am using Json.net, I got a class as following

public class RecordAlias
    {   
        [JsonProperty(PropertyName = "eId", Required = Required.Always)]
        public string EntityId { get; set; }

        [JsonProperty(PropertyName = "aId", Required = Required.AllowNull)]
        public string AliasId { get; set; }

        [JsonProperty(PropertyName = "iSd", Required = Required.AllowNull)]
        public bool IsSelected { get; set; }
    }

So that following json can be deserialized even through some items don't have property "iSd" in json string, I would expect a default value of that type should be populated if not present, for example, IsSelected should be false except last item

      [{
        "eId" : "30022004",
        "aId" : "1"
    }, {
        "eId" : "30021841",
        "aId" : "1"
    }, {
        "eId" : "30021848",
        "aId" : "1"
        "iSd" : true
    }
]

Any idea how can I achieve this?

like image 698
Ming Avatar asked Sep 19 '11 14:09

Ming


1 Answers

I made a little table for the Required enum values and their effect based on the Required documentation:

                       | Must be present | Can be Null value
-----------------------+-----------------+------------------
Required.Default       |                 |         ✓    
-----------------------+-----------------+------------------
Required.AllowNull     |        ✓        |         ✓    
-----------------------+-----------------+------------------
Required.Always        |        ✓        |            
-----------------------+-----------------+------------------
Required.DisallowNull  |                 |          

In your case the isD is optional you should have used Required.Default (or Required.DisallowNull). Using Required.AllowNull also makes the isD mandatory and it thus throws the Exception when it's missing.

Note that in this case it makes no sense to differentiate between "Optional and may be null" (Required.Default) or "Optional but may not be null" (Required.DisallowNull) because bool is a value type that cannot be null. If you wanted to allow null values you need to use a nullable value type (bool?), however then the default value (when the value is not present) would be null, except when you set it manually (for example to false):

[JsonProperty(PropertyName = "iSd", Required = Required.Default)]
public bool? IsSelected { get; set; } = false;
like image 104
MSeifert Avatar answered Sep 20 '22 18:09

MSeifert