Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing Json to list of objects in C# with Newtonsoft

So I am struggeling to parse the following JSON string. Even after researching many questions here on StackOverflow.

Json

[
  {
    "text": {
      "0": "Element 1"
    },
    "cascade": [],
    "val": "1"
  },
  {
    "text": {
      "0": "Element 2"
    },
    "cascade": [],
    "val": "2"
  },
  {
    "text": {
      "0": "Element 3"
    },
    "cascade": [],
    "val": "3"
  },
  {
    "text": {
      "0": "Unknown"
    },
    "cascade": [],
    "val": "0"
  }
]

The class I created for this looks like this:

Options.cs

using System.Collections.Generic;

namespace App.Models
{
  public class Options
  {
    public ICollection<IDictionary<string, string>> text { get; set; }
    public List<string> cascade { get; set; }
    public string val { get; set; }
  }
}

For running the deserialization I've written the following line:

List<Options> optionList = JsonConvert.DeserializeObject<List<Options>>(inputString);

I'm getting the following exceptions when I try to run the code:

Newtonsoft.Json.JsonSerializationException: Timeout exceeded getting exception details

like image 529
betaros Avatar asked Jan 23 '26 20:01

betaros


1 Answers

You problem is reading the "text" object. From you sample, it contains key/value pairs of string type both. There is no reason to use ICollection there, but only Dictionary<string, string>

public class Options
{
    public Dictionary<string, string> text { get; set; }
    public List<string> cascade { get; set; }
    public string val { get; set; }
}

Update: Since your sample JSON does not include data about the cascade member (only an empty array), it might be safe declaring it as a list of objects List<object>.

like image 97
EylM Avatar answered Jan 25 '26 12:01

EylM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!