Automatic parameterized constructor selection during JsonCovertor deserialization

I am using json.NET to deserialize my json string for my model. below is what I am trying to achieve, please advice what is best.

When there is no data, my answer looks below   json string = "{\"message\":\"SUCCESS\",\"result\":null}"

the result is ultimately attached to the species. Therefore, when the answer is null, I would like to initialize my view using the default values ​​of the model. And so I would like to call the default constructor when deserializing. The default constructor looks below.

    public ProfileModel()
    {
        this.DefaultTab = DefaultTabOption.PROFILE;
        this.DataLoadPosition = new DataLoadPositionOptionsModel();
        this.DataLayout = new DataLayoutOptionsModel();
        this.NAData = new NADataOptionsModel();
        this.DataTable = new DataDisplayOptionsModel();
    }

But when there is data, the answer is as follows.

{"message":"SUCCESS","result":{"dataLayout":{"vertical":false},"dataLoadPosition":{"cell":"B2","cursorLocation":false},"dataTable":{"decimalPts":1},"defaultTab":"BROWSE","naData":{"custom":"","naDataOption":"FORWARDFILL"}}}

In this case, I would like to call my parameterized constructor so that the models are correctly initialized.

Deserialization Code:

        using (StreamReader reader = new StreamReader(responseStream))
        {
           var t = JsonConvert.DeserializeObject<T>(reader.ReadToEnd());                
           return t;
        }

T - , . .

public ProfileModel(DefaultTabOption defaultTabModel,
                    DataLoadPositionOptionsModel dataLoadPositionOption ,
                    DataLayoutOptionsModel dataLayoutOptios ,
                    NADataOptionsModel naDataOptions ,
                    DataDisplayOptionsModel dataTableOptions)
{
    this.DefaultTab = defaultTabModel;
    this.DataLoadPosition = dataLoadPositionOption;
    this.DataLayout = dataLayoutOptios;
    this.NAData = naDataOptions;
    this.DataTable = dataTableOptions;
}

, , null , . ConstructorHandling, NullValueHandling, .

+4
1

.

public sealed class ProfileModel
{
    public ProfileModel()
    {
        DataLayout = new DataLayoutOptionsModel();
    }

    public ProfileModel(DataLayoutOptionsModel dataLayout)
    {
        DataLayout = dataLayout;
    }

    public DataLayoutOptionsModel DataLayout { get; private set; }
}

public sealed class DataLayoutOptionsModel
{
    public bool Vertical { get; set; }
}

public class ResultModel
{
    public string Message { get; set; }
    public ProfileModel Result { get; set; }
}

, JsonConverter,

public sealed class MyJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(ProfileModel).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
    {
        ProfileModel target;
        JObject jObject = JObject.Load(reader);

        JToken resultToken = jObject["Result"];
        //This is result null check
        if (resultToken.Type == JTokenType.Null)
        {
            target = new ProfileModel();
        }
        else
        {
            var optionsModel = resultToken["DataLayout"].ToObject<DataLayoutOptionsModel>();
            target = new ProfileModel(optionsModel);
        }

        serializer.Populate(jObject.CreateReader(), target);
        return target;
    }

    public override void WriteJson(JsonWriter writer,
        object value,
        JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

, :

[Fact]
public void Test()
{
    string tinyJsonl = "{\"Message\":\"SUCCESS\",\"Result\":null}";
    var defaultProfile = JsonConvert.DeserializeObject<ProfileModel>(tinyJsonl, new MyJsonConverter());
    Assert.False(defaultProfile.DataLayout.Vertical);

    string fullJson = "{\"Message\":\"SUCCESS\",\"Result\":{\"DataLayout\":{\"Vertical\":true}}}";
    var customProfile = JsonConvert.DeserializeObject<ProfileModel>(fullJson, new MyJsonConverter());
    Assert.True(customProfile.DataLayout.Vertical);
}
+3

Source: https://habr.com/ru/post/1540910/


All Articles