我正在尝试为需要发送/接收的JSON编写一些C#包装类。在一个例子中,我收到了一个混合类型的多维数组:
stops: [
[0.1, "#55BF3B"],
[0.5, "#DDDF0D"],
[0.9, "#DF5353"]
]
如何在类属性中表示?
[JsonProperty("stops")]
public WhatType?[] Stops { get; set; }
我真正喜欢的是如下课程:
public class Stop
{
public decimal Value { get; set; }
public string Color { get; set; }
}
那将序列化/反序列化为数组(没有属性名称):
[.1, "#000000"]
然后我的Stops属性可能只是一个Stop数组。但是,即使使用自定义转换器,我也不确定这是否可行。有什么想法吗?
答案 0 :(得分:5)
是的,这几乎是您使用JsonConverter
的情况的教科书示例
这是代码的样子:
class StopConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Stop));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JArray ja = JArray.Load(reader);
Stop stop = new Stop();
stop.Value = (decimal)ja[0];
stop.Color = (string)ja[1];
return stop;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JArray ja = new JArray();
Stop stop = (Stop)value;
ja.Add(stop.Value);
ja.Add(stop.Color);
ja.WriteTo(writer);
}
}
要使用转换器,只需使用Stop
属性装饰[JsonConverter]
类,如下所示:
[JsonConverter(typeof(StopConverter))]
public class Stop
{
public decimal Value { get; set; }
public string Color { get; set; }
}
然后,一切都应该"只是工作"。这是一个往返演示:
class Program
{
static void Main(string[] args)
{
string json = @"
{
""stops"":
[
[0.1, ""#55BF3B""],
[0.5, ""#DDDF0D""],
[0.9, ""#DF5353""]
]
}";
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
foreach (Stop stop in obj.Stops)
{
Console.WriteLine("Value: " + stop.Value);
Console.WriteLine("Color: " + stop.Color);
Console.WriteLine();
}
json = JsonConvert.SerializeObject(obj, Formatting.Indented);
Console.WriteLine(json);
}
}
class RootObject
{
[JsonProperty("stops")]
public List<Stop> Stops { get; set; }
}
[JsonConverter(typeof(StopConverter))]
public class Stop
{
public decimal Value { get; set; }
public string Color { get; set; }
}
输出:
Value: 0.1
Color: #55BF3B
Value: 0.5
Color: #DDDF0D
Value: 0.9
Color: #DF5353
{
"stops": [
[
0.1,
"#55BF3B"
],
[
0.5,
"#DDDF0D"
],
[
0.9,
"#DF5353"
]
]
}