Home > front end >  ServiceStack Deserialize Json with Required Attribute
ServiceStack Deserialize Json with Required Attribute

Time:08-13

I'm trying to get the deserialization to throw an exception if a certain JSON attribute is missing. ex. This should deserialize fine (and it does):

{
    "Property1": 0,
    "Property2": "value",
    "Property3": {
        "ChildProperty1": 0,
        "ChildProperty2": "value",
    }
}

but I would like this to throw an exception (because ChildProperty1 is missing):

{
    "Property1": 0,
    "Property2": "value",
    "Property3": {
        "ChildProperty2": "value",
    }
}

I'm currently deserializing the JSON string like this:

var settings = settingsString.FromJson<Settings>();

My Settings Class looks like this:

[DataContract]
public record Settings
{
    [DataMember]
    public int Property1 { get; init; }

    [DataMember]
    public string Property2 { get; init; }

    [DataMember]
    public MyType Property3 { get; init; }
}

[DataContract]
public record MyType
{
    [DataMember]
    public int ChildProperty1 { get; init; }

    [DataMember]
    public string ChildProperty2 { get; init; }
}

I've tried to decorate the properties with [DataMember(IsRequired = true)] and [DataMember, ServiceStack.DataAnnotations.Required] but neither had any affect.

I've also read this page about the BindRequiredAttribute but I'm guessing that wouldn't affect the ServiceStack deserializer either.

Is there a way to accomplish this with ServiceStack or might I need to use a different deserializer to do this more easily?

CodePudding user response:

Have a look at the SerializationHookTests.cs which shows that you can use different hook attributes to run different code during serialization/deserialization so you should be able to add custom validation in [OnDeserialized] method:

public class HookExamples
{
    [OnDeserializing]
    protected void OnDeserializing(StreamingContext ctx)
    {
        // Will be executed when deserializing starts
    }

    [OnDeserialized]
    protected void OnDeserialized(StreamingContext ctx)
    {
        // Will be executed when deserializing finished
    }

    [OnSerializing]
    protected void OnSerializing(StreamingContext ctx)
    {
        // Will be executed when serializing starts
    }

    [OnSerialized]
    protected void OnSerialized(StreamingContext ctx)
    {
       // Will be executed when serializing finished
    }
}

  • Related