我正在使用JSON.net,我试图从开源UnitClassLibrary序列化和反序列化一个距离对象。目前,我有一个对象序列化为以下JSON:
{
"ThirtySecondsOfAnInch": 454,
"SixteenthsOfAnInch": 227,
"EighthsOfAnInch": 113.5,
"QuartersOfAnInch": 56.75,
"HalvesOfAnInch": 28.375,
"Inches": 14.1875,
"Feet": 1.1822916666666667,
"Yards": 0.3940972222222222,
"Miles": 0.00022391887626262627,
"Millimeters": 360.36249999999995,
"Centimeters": 36.03625,
"Meters": 0.3603625,
"Kilometers": 0.0003603625,
"Architectural": "1'2 3/16""
}
我可以取其中任何一个,并使用这个类将其转换为距离对象。例如,对于最后一个体系结构字符串,我可以使用以下构造函数:
Distance newDistance = new Distance("1'2 3/16"");
或者,使用32英寸,我可以这样做:
Distance newDistance = new Distance(DistanceType.ThirtySecond, 454.0);
然而,我不确定编写JsonConstructor (JSON.net可以专门使用的构造函数类型)的最佳方法是在传递带有JsonConvert.DeserializeObject<Distance>(json);
的JSON字符串时接受任何一种类型的输出。
我如何写一个构造函数来接受一个新的距离对象?
下面是一个JsonConverter示例。
public class DistanceConverter : JsonConverter
{
private readonly IDictionary<string, DistanceType> _distanceTypeMap;
public DistanceConverter()
{
_distanceTypeMap = new Dictionary<string, DistanceType>
{
{"Meters", DistanceType.Meter},
{"Yards", DistanceType.Yard}
};
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Distance distance = value as Distance;
if (distance == null)
{
writer.WriteNull();
return;
}
writer.WriteStartObject();
foreach (KeyValuePair<string, DistanceType> pair in _distanceTypeMap)
{
writer.WritePropertyName(pair.Key);
writer.WriteValue(distance.GetValue(pair.Value));
}
writer.WriteEndObject();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Distance result = null;
while (reader.Read())
{
var key = reader.Value;
string value = reader.ReadAsString();
if (result == null && key != null)
{
DistanceType distanceType;
if (_distanceTypeMap.TryGetValue(key.ToString(), out distanceType))
{
double parsedValue = JToken.Parse(value).Value<double>();
result = new Distance(distanceType, parsedValue);
}
}
}
return result;
}
public override bool CanConvert(Type objectType)
{
return typeof(Distance) == objectType;
}
}
这个目前有问题。我不明白为什么即使我在反序列化中创建对象,也会得到零距离。下面是查看结果的几个测试:
更新:我在再次阅读时修复了错误。它目前可以工作,但当你向字典中添加其他单位时,可能会出现异常。
public class DistanceConverterTests
{
private JsonSerializerSettings _jsonSerializerSettings;
[SetUp]
public void Setup()
{
_jsonSerializerSettings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new DistanceConverter() }
};
}
[Test]
public void DeserializeTest()
{
string json = File.ReadAllText("data.json");
var distance = JsonConvert.DeserializeObject<Distance>(json, _jsonSerializerSettings);
distance.Meters.Should().BeInRange(0.360, 0.361);
}
[Test]
public void SerializeTest()
{
Distance distance = new Distance(DistanceType.Meter, 2.20);
string json = JsonConvert.SerializeObject(distance, _jsonSerializerSettings);
Console.WriteLine(json);
}
}