libra
libra

Reputation: 683

Customized JSON.NET converter that convert string to type

So basically I have this class in c# that I want to deserialize to, Here is the class:

public class Data {
    public string Name{get;set;}
    public string Label{get;set;}
    public string Unit{get;set;}
    public int Precision{get;set;}

        [JsonPropertyAttribute("type")]
        public Type DataType{get;set;}
}

And my Json String looks like this:

{
    "name": "ACCurrent",
    "label": "ACCurrent",
    "unit": "A",
    "precision": 2,
    "type": "float"
}

But the I don't know how to write a custom converter to convert "float" to typeof(float). I saw the documentation and I think I need to work on the WriteJson method under converter. But I don't quite understand how I should do it. Any help would be appreciated!

Upvotes: 2

Views: 1429

Answers (1)

Patryk
Patryk

Reputation: 39

My proposition is to create Custom Json Converter. Please be aware that this Converter will be used during deserialization and serialization time. I only implemented deserialization.

public class Data
{
    public string Name { get; set; }
    public string Label { get; set; }
    public string Unit { get; set; }
    public int Precision { get; set; }

    [JsonPropertyAttribute("type")]
    [JsonConverter(typeof(DataTypeConverter))]
    public Type DataType { get; set; }
}

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

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        var value = token.Value<string>();
        if (value == "float")
        {
            return typeof (float);
        }
        return null;

    }

    public override bool CanConvert(Type objectType)
    {
        throw new NotImplementedException();
    }
}

Some Test Code:

    public static string GetJsonString()
    {
        return "{ \"name\": \"ACCurrent\", " +
               "  \"label\": \"ACCurrent\"," +
               "  \"unit\": \"A\"," +
               "  \"precision\": 2," +
               "  \"type\": \"float\" }";
    }


    [Test]
    public void Deserialize_String_To_Some_Data()
    {
        var obj = JsonConvert.DeserializeObject<Data>(RawStringProvider.GetJsonString());
        Assert.AreEqual(typeof(float), obj.DataType);
    }

I tried to use Type.GetType("someTypeString") but this will not work. Type.GetType() thread.

Upvotes: 2

Related Questions