根据元素的内容将JSON序列化为不同的元素

时间:2015-02-14 22:10:41

标签: c# json json.net

我正在尝试将具有以下示例内容的项目的JSON文件解析为不同的项目:

{
    "PM00000001": { "description": "Manufacturing","cost": -1,"group":"Manufacturing","WeldAngleDegrees": 60},
    "PM00000010": {"description": "Plate Roll","cost": 90,"unit": "hr","group": "Roll","setup": 0.5,"speed": 0.4},
    "PM00000011": {"description": "Weld SAW","cost": 90,"unit": "hr","group": "Weld","width": 0.5,"thickness": 50}
}

每个项目都有描述,成本和组。其余属性取决于组。在上面的示例中,制造有" WeldAngleDegrees",Roll有setupspeed,而Weld有widththickness

我正在尝试使用JSON.NET来解析此文件。

现在我正在这样做:

string text = System.IO.File.ReadAllText(ofd.FileName);
Dictionary<string, Item> deserializedProduct = JsonConvert.DeserializeObject<Dictionary<string, Item>>(text, new ItemConverter());

public class Item
{
    public string description { get; set; }
    public double cost { get; set; }
    public string group { get; set; }
}

public class ManufacturingItem : Item
{
    public string WeldAngleDegrees { get; set; }
}

public class ItemConverter : CustomCreationConverter<Item>
{
    public override Item Create(Type objectType)
    {
        return new ManufacturingItem();
    }
}

ItemConverter中是否有办法找出哪个&#34;组&#34;该项属于创建正确的项类型?

有更简单的方法吗?

2 个答案:

答案 0 :(得分:2)

不是从ItemConverter派生CustomCreationConverter<T>,而是从JsonConverter派生出来;然后您将可以通过阅读器访问JSON。您可以将对象数据加载到JObject,然后检查group属性以确定要创建的类。以下是代码的外观:

public class ItemConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Item);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jo = JObject.Load(reader);
        string group = (string)jo["group"];
        if (group == "Manufacturing")
        {
            return jo.ToObject<ManufacturingItem>();
        }
        else if (group == "Roll")
        {
            return jo.ToObject<RollItem>();
        }
        else if (group == "Weld")
        {
            return jo.ToObject<WeldItem>();
        }
        throw new JsonSerializationException("Unexpected item (group) type");
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

小提琴:https://dotnetfiddle.net/8ZIubu

答案 1 :(得分:1)

只需将json反序列化为字典,然后根据group的值解释值。

var dict = JsonConvert.DeserializeObject<Dictionary<string, MyItem>>(json);

public class MyItem
{
    public string Description { get; set; }
    public int Cost { get; set; }
    public string Group { get; set; }
    public int WeldAngleDegrees { get; set; }
    public string Unit { get; set; }
    public double Width { get; set; }
    public int Thickness { get; set; }   
    public double Speed { get; set; }
    public double Setup { get; set; } 

}