将多个值反序列化为单个属性



我有一个JSON响应,其中包括几个标志:

{"df":1,"dr":0,"pf":0,"pr":0,"ft":0,"rt":1}

我想将其反序列化为标志枚举:

public class Foo {
    public Doors Doors { get; set; }
    public Trunk Trunks { get; set; }
}

df、dr、pf、pr应反序列化为Doors标志枚举,而ft、rt应进入Trunks。我希望这是一个自定义代码来做出决定。我要找的是一个可以让我说的东西:

[JsonProperty("df,dr,pf,pr"), JsonConverter(typeof(DoorsConverter))]
public Doors Door { get; set; }

这将使我能够处理基于这些价值观的房产建设。这种事情存在吗?还是我一直在把个人财产推向非公共领域,并在事后建造财产?

我同意@JeffMercado的观点,即处理此问题的最佳方法是创建一个处理整个类的自定义转换器。您在评论中说,创建这样一个转换器时遇到了麻烦,因为您不想编写代码来处理所有其他类属性(问题中未显示),因为它们不需要任何特殊处理。为此,我提出了一个转换器的想法,它将使用JSON.Net对所有标准属性的常用机制来序列化/反序列化对象,但随后会专门处理DoorsTrunks枚举字段。由于我不知道你的其他财产叫什么,我只编了一些与汽车有关的财产。为了与该主题保持一致,我还将您的Foo类重命名为Car

下面是这个例子的类和枚举定义:

public class Car
{
    [JsonIgnore]
    public Door Doors { get; set; }
    [JsonIgnore]
    public Trunk Trunks { get; set; }
    [JsonProperty("make")]
    public string Make { get; set; }
    [JsonProperty("model")]
    public string Model { get; set; }
    [JsonProperty("year")]
    public int Year { get; set; }
    [JsonProperty("MSRP")]
    public decimal MSRP { get; set; }
}
[Flags]
public enum Door 
{
    None = 0,
    DriverSideFront = 1,
    DriverSideRear = 2,
    PassengerSideFront = 4,
    PassengerSideRear = 8 
}
[Flags]
public enum Trunk
{
    None = 0,
    Front = 1, 
    Rear = 2
}

这是自定义转换器的代码:

public class CarConverter : JsonConverter
{
    private static Dictionary<string, Door> doorMap;
    private static Dictionary<string, Trunk> trunkMap;
    static CarConverter()
    {
        doorMap = new Dictionary<string, Door>();
        doorMap.Add("df", Door.DriverSideFront);
        doorMap.Add("dr", Door.DriverSideRear);
        doorMap.Add("pf", Door.PassengerSideFront);
        doorMap.Add("pr", Door.PassengerSideRear);
        trunkMap = new Dictionary<string, Trunk>();
        trunkMap.Add("ft", Trunk.Front);
        trunkMap.Add("rt", Trunk.Rear);
    }
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Car));
    }
    public override object ReadJson(JsonReader reader, Type objectType, 
                                    object existingValue, JsonSerializer serializer)
    {
        JObject jo = JObject.Load(reader);
        Car car = jo.ToObject<Car>();
        car.Doors = GetDoors(jo);
        car.Trunks = GetTrunks(jo);
        return car;
    }
    private Door GetDoors(JObject obj)
    {
        Door doors = Door.None;
        foreach (KeyValuePair<string, Door> kvp in doorMap)
        {
            if (obj[kvp.Key].Value<int>() == 1)
            {
                doors |= kvp.Value;
            }
        }
        return doors;
    }
    private Trunk GetTrunks(JObject obj)
    {
        Trunk trunks = Trunk.None;
        foreach (KeyValuePair<string, Trunk> kvp in trunkMap)
        {
            if (obj[kvp.Key].Value<int>() == 1)
            {
                trunks |= kvp.Value;
            }
        }
        return trunks;
    }
    public override void WriteJson(JsonWriter writer, object value, 
                                   JsonSerializer serializer)
    {
        Car car = (Car)value;
        JObject obj = JObject.FromObject(value);
        AddDoors(obj, car.Doors);
        AddTrunks(obj, car.Trunks);
        obj.WriteTo(writer);
    }
    private void AddDoors(JObject obj, Door doors)
    {
        foreach (KeyValuePair<string, Door> kvp in doorMap)
        {
            obj.Add(kvp.Key, ((doors & kvp.Value) != Door.None) ? 1 : 0);
        }
    }
    private void AddTrunks(JObject obj, Trunk trunk)
    {
        foreach (KeyValuePair<string, Trunk> kvp in trunkMap)
        {
            obj.Add(kvp.Key, ((trunk & kvp.Value) != Trunk.None) ? 1 : 0);
        }
    }
}

最后,这里有一个显示用法的测试程序:

static void Q18066528()
{
    string json = @"{""df"":1,""dr"":0,""pf"":0,""pr"":1,""ft"":0,""rt"":1,
       ""make"":""Chevrolet"",""model"":""Corvette"",""year"":2013,""MSRP"":49600}";
    JsonSerializerSettings settings = new JsonSerializerSettings 
    { 
        Converters = new List<JsonConverter> { new CarConverter() } 
    };
    Car car = JsonConvert.DeserializeObject<Car>(json, settings);
    Console.WriteLine("Model: " + car.Model);
    Console.WriteLine("Year: " + car.Year);
    Console.WriteLine("Doors: " + car.Doors);
    Console.WriteLine("Trunks: " + car.Trunks);
    string json2 = JsonConvert.SerializeObject(car, settings);
    Console.WriteLine(json2);
}

以上输出:

Model: Corvette
Year: 2013
Doors: DriverSideFront, PassengerSideRear
Trunks: Rear
{"make":"Chevrolet","model":"Corvette","year":2013,"MSRP":49600.0,"df":1,"dr":0,
"pf":0,"pr":1,"ft":0,"rt":1}

重要提示:你可能会想用[JsonConverter(typeof(CarConverter))]来修饰Car类,但不要这样做。如果你这样做了,那么CarConverter就不能正常工作:转换器最终会递归地调用自己,直到它用StackOverflowException出错。(手动处理所有类属性的转换器不会有这个问题。)

JSON.NET最近添加了一个扩展数据概念,类似于我们在WCF数据契约中获得的概念。有了这个,我可以添加一个额外的属性和方法来处理它:

[JsonExtensionData]
public IDictionary<string, JToken> ExtensionData;
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
    Doors = ExtensionData.ContainsKey("df") && Convert.ToBoolean(Convert.ToInt16(ExtensionData["df"]))
        ? Doors | Door.DriverSideFront
        : Doors & ~Door.DriverSideFront;
    Doors = ExtensionData.ContainsKey("dr") && Convert.ToBoolean(Convert.ToInt16(ExtensionData["dr"]))
        ? Doors | Door.DriverSideRear
        : Doors & ~Door.DriverSideRear;
    Doors = ExtensionData.ContainsKey("pf") && Convert.ToBoolean(Convert.ToInt16(ExtensionData["pf"]))
        ? Doors | Door.PassengerSideFront
        : Doors & ~Door.PassengerSideFront;
    Doors = ExtensionData.ContainsKey("pr") && Convert.ToBoolean(Convert.ToInt16(ExtensionData["pr"]))
        ? Doors | Door.PassengerSideRear
        : Doors & ~Door.PassengerSideRear;
    Trunks = ExtensionData.ContainsKey("ft") && Convert.ToBoolean(Convert.ToInt16(ExtensionData["ft"]))
        ? Trunks | Trunk.Front
        : Trunks & ~Trunk.Front;
    Trunks = ExtensionData.ContainsKey("rt") && Convert.ToBoolean(Convert.ToInt16(ExtensionData["rt"]))
        ? Trunks | Trunk.Rear
        : Trunks & ~Trunk.Rear;
    ExtensionData.Remove("dt");
    ExtensionData.Remove("dr");
    ExtensionData.Remove("pf");
    ExtensionData.Remove("pr");
    ExtensionData.Remove("ft");
    ExtensionData.Remove("rt");
}

这适用于读取场景。还没有研究写作场景以及这将如何改变事情。

相关内容

  • 没有找到相关文章

最新更新