0

I have some JSon that I am converting to an object using the ToObject method.

A part of this Json has a repeated element which is correctly represented as an array in the Json text. When I convert this it correctly is mapped to the C# object

public IList<FooData> Foo { get; set; }

But when I only have 1 element I get an error saying that the Json that I am trying to Parse into an object is not an array because it does not have [] around it.

Does Json.NET support single element arrays?

Sachin Kainth
  • 45,256
  • 81
  • 201
  • 304
  • 1
    Single element array in JSON still have `[]` around the element. – MarcinJuraszek Mar 20 '15 at 16:11
  • possible duplicate of [How to handle both a single item and an array for the same property using JSON.net](http://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n) – Andrew Whitaker Mar 20 '15 at 16:12
  • If it doesn't have `[]` it isn't a valid JSON array, so the message is correct. What's generating the JSON your trying to parse? I'd suggest that, that code is wrong, not Json.Net – Liam Mar 20 '15 at 16:15
  • There is a very similar question and a good solution for this: http://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n – ozanmut Feb 03 '16 at 08:11

2 Answers2

4

But when I only have 1 element I get an error saying that the Json that I am trying to Parse into an object is not an array because it does not have [] around it.

If a JSON text has no [] around, then it's not a single-element array: actually it's an object (for example: { "text": "hello world" }).

Try using JsonConvert.DeserializeObject method:

jsonText = jsonText.Trim();

// If your JSON string starts with [, it's an array...
if(jsonText.StartsWith("["))
{
    var array = JsonConvert.DeserializeObject<IEnumerable<string>>(jsonText);
}
else // Otherwise, it's an object...
{
    var someObject = JsonConvert.DeserializeObject<YourClass>(jsonText);
}

It can also happen that JSON text contains a literal value like 1 or "hello world"... but I believe that these are very edge cases...

For the above edge cases just deserialize them with JsonConvert.DeserializeObject<string>(jsonText) for example (replace string with int or whatever...).

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
1

Make sure you are enclosing your JSON single item array is still specified as an array using array notation []

BenM
  • 4,218
  • 2
  • 31
  • 58