neuecc / Utf8Json

Definitely Fastest and Zero Allocation JSON Serializer for C#(NET, .NET Core, Unity, Xamarin).
MIT License
2.36k stars 267 forks source link

About difference between a json property null and no property #149

Open jkbrito opened 5 years ago

jkbrito commented 5 years ago

How do we deal with the difference between a json property being null, and there is no property? For example:

public class ObjectOne {

    [JsonProperty(Name = "propertyOne")]
    public string PropertyOne {get;set;}

    [JsonProperty(Name = "propertyTwo")]
    public string PropertyTwo {get;set;}

}
{"propertyOne": null, "propertyTwo":null}
{"propertyOne": null }

We could create a struct that contains the information of whether a property exists or not in deserialization. For exemplo.

 public struct JsonMetadata<T>
    {
        public JsonMetadata(T obj)
        {
            HasProperty = true;
            Value = obj;
        }

        public bool HasProperty { get; }  
        public T Value { get; }

        public static implicit operator T(JsonMetadata<T> jMetadata) => jMetadata.Value;
        public static implicit operator JsonMetadata<T>(T value) => new JsonMetadata<T>(value);
    }

 public class ObjectOne {

    [JsonProperty(Name = "propertyOne")]
    public string PropertyOne {get;set;}

    [JsonProperty(Name = "propertyTwo")]
    public JsonMetadata<string> PropertyTwo {get;set;}

}

Is this possible?