#Problem with Deserializing an JSON object into a class that inherits values from abstract class

1 messages · Page 1 of 1 (latest)

nova wadi
#
{
  "width": 2,
  "height": 2,
  "_items": [
    {
      "Key": {
        "x": 1,
        "y": 0,
        "magnitude": 1.0,
        "sqrMagnitude": 1
      },
      "Value": {
        "width": 2,
        "height": 2,
        "_items": [],
        "itemType": 0,
        "itemPrefab": null,
        "icon": null,
        "itemName": "veeeery cool backpack",
        "description": null,
        "sizeX": 2,
        "sizeY": 2,
        "mass": 0.0,
        "stackSize": 0,
        "maxStackSize": 0,
        "itemID": 0,
        "subItemId": 1
      }
    },
    {
      "Key": {
        "x": 1,
        "y": 2,
        "magnitude": 2.236068,
        "sqrMagnitude": 5
      },
      "Value": {
        "width": 2,
        "height": 2,
        "_items": [],
        "itemType": 0,
        "itemPrefab": null,
        "icon": null,
        "itemName": "veeeery cool backpack",
        "description": null,
        "sizeX": 2,
        "sizeY": 2,
        "mass": 0.0,
        "stackSize": 0,
        "maxStackSize": 0,
        "itemID": 0,
        "subItemId": 1
      }
    }
  ],
  "itemType": 0,
  "itemPrefab": null,
  "icon": null,
  "itemName": "cool backpack",
  "description": null,
  "sizeX": 2,
  "sizeY": 2,
  "mass": 0.0,
  "stackSize": 0,
  "maxStackSize": 0,
  "itemID": 10,
  "subItemId": 1
}```
error:
```JsonSerializationException: Could not create an instance of type Item. Type is an interface or abstract class and cannot be instantiated. Path '_items[0].Value.width', line 13, position 16.``` 
and my data structure:
```C#
public abstract class Item 
{
    // implementation specific
    public ItemType itemType;
    public GameObject itemPrefab;
    public Sprite icon;
    public string itemName, description;
    public int sizeX, sizeY;
    public float mass;
    public int stackSize;
    public int maxStackSize;
    public int itemID;
    public int subItemId;
}
#
public class Backpack : Item , IInventory
    {
        public int width, height;
        public List<KeyValuePair<Vector2Int, Item>> _items = new List<KeyValuePair<Vector2Int, Item>>();
}
#

also, I use Newtonsoft to serialize/deserialize objects

#

I found the sollution

#

closing