I am trying to parse into different items a JSON file that has items with the following example content:
{
"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}
}
Each item has a description, cost and group. The rest of the attributes depend on the group. In the example above Manufacturing has "WeldAngleDegrees", Roll has setup
and speed
, and Weld has width
and thickness
.
I am trying to use JSON.NET to parse this file.
Right now I am doing this:
string text = System.IO.File.ReadAllText(ofd.FileName);
Dictionary<string, Item> deserializedProduct = JsonConvert.DeserializeObject<Dictionary<string, Item>>(text, new ItemConverter());
with
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();
}
}
Is there a way in ItemConverter
to figure out which "group" the item belongs to to create the correct item type?
Is there an easier way to do this?