3

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

2
  • 1
    Try public Dictionary<string, string> text { get; set; } Commented Aug 15, 2019 at 10:08
  • 2
    if you paste your JSON into json2csharp.com it will suggest a data structure for you. It may not be the only way to do it, but it will suggest something which is likely to work. N.B. List<string> in your code seems inappropriate for "cascade", since it's an array in the JSON. Commented Aug 15, 2019 at 10:08

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

List<string> cascade seems inadvisble, since it's just an empty array in the JSON - we don't know what it could contain. List<object> might be safer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.