所以基本上我在 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 字符串看起来像这样:
{
"name": "ACCurrent",
"label": "ACCurrent",
"unit": "A",
"precision": 2,
"type": "float"
}
但是我不知道如何编写自定义转换器来将"float"转换为typeof(float(。我看到了文档,我认为我需要在转换器下处理 WriteJson 方法。但我不太明白我应该怎么做。任何帮助将不胜感激!
我的主张是创建自定义 JSON 转换器。请注意,此转换器将在反序列化和序列化期间使用。我只实现了反序列化。
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("someTypeString"(,但这不起作用。Type.GetType(( 线程。