2

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!

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
libra
  • 673
  • 1
  • 10
  • 30

1 Answers1

2

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.

Community
  • 1
  • 1
Patryk
  • 39
  • 7