Home > Back-end >  Deserializing JSON object array to List<MyOwnClass>
Deserializing JSON object array to List<MyOwnClass>

Time:01-02

I'm trying to read this JSON array:

[{"name":"lc_cash","slot":1,"info":"","type":"item","amount":591},{"name":"advancedlockpick","slot":2,"info":[],"type":"item","amount":19}]

This is my code:

File Inventory.cs

class Item {
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("slot")]
    public int Slot { get; set; }

    [JsonProperty("info")]
    public object Info { get; set; }

    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("amount")]
    public int Amount { get; set; }
}

class Inventory
{
    public List<Item> Item { get; set; }
}

File Form1.cs

Inventory inventory = new Inventory();
inventory = JsonSerializer.Deserialize<Inventory>(players.Inventory);

I'm getting this error:

System.Text.Json.JsonException: 'The JSON value could not be converted to Inventory. Path: $ | LineNumber: 0 | BytePositionInLine: 1.'

How can I read this correctly?

EDIT: testing with stackoverflow answers:

Main code:

List<Item> items = new List<Item>();
items = JsonSerializer.Deserialize<List<Item>>(players.Inventory);

Item class:

class Item {
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("slot")]
    public int Slot { get; set; }

    [JsonProperty("info")]
    public string Info { get; set; }

    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("amount")]
    public int Amount { get; set; }
}

Result: It's not throwing exception anymore but reading only 0 and nill

enter image description here

CodePudding user response:

you will have to fix your json, one of the property info has value string, another has array. you have to select something one, string for example

var jsonParsed = JArray.Parse(json);

foreach (var item in jsonParsed)
{
if (((JObject)item)["info"].GetType().Name == "JArray")
 ((JObject)item)["info"] = string.Empty;
}

List<Item> items = jsonParsed.ToObject<List<Item>>();

result

[
  {
    "name": "lc_cash",
    "slot": 1,
    "info": "",
    "type": "item",
    "amount": 591
  },
  {
    "name": "advancedlockpick",
    "slot": 2,
    "info": "",
    "type": "item",
    "amount": 19
  }
]

CodePudding user response:

as long as the information here is right, you gave us a json array string. the inventory is an object with an array, so the simple solution will be this:

  Inventory inventory = new Inventory();
  inventory.Item = JsonSerializer.Deserialize<List<Item>>(players.Inventory);

important to mention that since Item is a list, you should use plural name

  • Related