简体   繁体   中英

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

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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM