3

我有一个 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; }

这将使我能够根据这些值来处理财产的建设。这种类型的事情是否存在,或者我是否坚持将单个属性推入非公共领域并在事后构建属性?

4

2 回答 2

3

我同意@JeffMercado 的观点,处理这个问题的最好方法是创建一个处理整个类的自定义转换器。您在评论中说您已经挂断了创建这样的转换器,因为您不想编写代码来处理所有其他类属性(未在您的问题中显示),因为它们不需要任何特殊处理。为此,我提出了一个转换器的想法,该转换器将使用 JSON.Net 的所有标准属性的常用机制来序列化/反序列化您的对象,然后专门处理DoorsTrunksenum 字段。由于我不知道你的其他属性叫什么,我只是编造了一些与汽车有关的。我还将您的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}

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

于 2013-08-05T23:46:49.547 回答
0

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");
}

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

于 2013-08-05T21:00:28.693 回答