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

Require properties #70

Open kspeakman opened 6 years ago

kspeakman commented 6 years ago

How do I make all properties required on deserialization? So if the property is missing or set to null in json, then deserialization fails. The normal behavior is to return a default value. Using this configuration:

// F#
let resolver =
    CompositeResolver.Create
        (FSharpResolver.Instance, StandardResolver.ExcludeNullCamelCase)

type IntTest = { I : int }

let test () =
    let bytes = Encoding.UTF8.GetBytes("{}")
    JsonSerializer.Deserialize<IntTest>(bytes, resolver)
        |> Console.WriteLine
        // prints "{ I = 0 }"

I have a use case where missing/null data means the request is malformed and I return a 400 Bad Request. Since I'm using F#, missing/null properties are only ok if the type is Option<T> (similar to Nullable<T> except it works for ref types too). I had to use a custom resolver in JsonNet. I'm just not sure how to make them required on Utf8Json.

neuecc commented 6 years ago

Currently Utf8Json does not have like ItemRequired = Required.Always option. So can not do it.

kspeakman commented 6 years ago

Seems null properties could be detected with a formatter. Missing properties are not as simple. The deserialization would need to keep track of properties encountered as it parsed the json. Once the json has been fully read, if any properties remain unseen then it would throw. Looks like to do this I would need to make my own DynamicObjectResolver, especially the BuildDeserialize method. 😨

Could required properties setting be added to Utf8Json? This is primarily applicable for F# currently, because it allows me to express whether data is optional using the type system. Example: type of string option means it is a string but may be absent or null in JSON, and I must handle the absent case. But perhaps soon this will apply equally to C# with nullable reference types. In this case, specifying string? type would mean the property may be absent or null in the JSON and hints to me that I should handle the null case. Either way, it is very convenient to let the type declaration express whether or not it is required.

Separate thing: I created a version of GuidBits which will read Base64url-encoded guids. Here is a gist.

Temtaime commented 4 years ago

Still not fixed? It is a 2020 and i still can pass garbage as json and get a class with all nulls.

DamianSuess commented 4 years ago

Any chance on supporting System.ComponentModel.DataAnnotations which has [Required]? This is used by ASP.Net