所以基本上我在c#中有这个类要反序列化,这是类:
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;}
}
我的Json String看起来像这样:
{
"name": "ACCurrent",
"label": "ACCurrent",
"unit": "A",
"precision": 2,
"type": "float"
}
但我不知道如何编写自定义转换器将“float”转换为typeof(float)。我看到了文档,我想我需要在转换器下处理WriteJson方法。但我不太明白我应该怎么做。任何帮助将不胜感激!
答案 0 :(得分:2)
我的主张是创建Custom Json Converter。请注意,此转换器将在反序列化和序列化时使用。我只实现了反序列化。
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();
}
}
一些测试代码:
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);
}
我尝试使用Type.GetType(&#34; someTypeString&#34;)但这不起作用。 Type.GetType() thread.