所以基本上我在 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() thread.
关于c# - 自定义 JSON.NET 转换器,将字符串转换为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42052461/