5

I'm trying to deserialize a JSON array to a string list with:

Newtonsoft.Json.Linq.JArray jsonResponse = JsonConvert.DeserializeObject(result) as Newtonsoft.Json.Linq.JArray;
List<string> response = jsonResponse.ToObject<List<string>>();

The JSON has the following structure:

[["No Es Posible Importar Dos Numeros De Servicios Iguales","No Es Posible Importar Dos Codigos Iguales"]]

But that throws the following error:

Error reading string. Unexpected token: StartArray. Path '[0]'.

How I can deserialize the object without errors?

4
  • 2
    why does your json start with two [[? did you intend to have an array inside an array? Commented Mar 27, 2018 at 22:42
  • It's a nested, jagged array so do var lists = JsonConvert.DeserializeObject<List<List<string>>(result). There's no need for the intermediate JArray representation by the way. Commented Mar 27, 2018 at 22:45
  • @Claies i dont now, im receiving the string from a web service, when i put this in a JSON viewer works fine Commented Mar 27, 2018 at 22:45
  • it's a list of lists of strings, so you either need to use the option @dbc mentioned, or List<List<string>> response = jsonResponse.ToObject<List<List<string>>>() Commented Mar 27, 2018 at 22:48

3 Answers 3

4

Thanks!!!

i followed the recommendations in the comments and all is working fine.

i only changed the code to:

var jsonResponse = JsonConvert.DeserializeObject<List<List<string>>>(result);

to get a list of lists.

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

Comments

1

This should work:-

var list = JArray.Parse(@"[[""a"", ""b"", ""c""]]").Values().Select(x => x.Value<string>()).ToList();

Hope that helps!

Comments

1

I had spent some time working on this with a C# Fiddle (I love these for collaboration) while you got it running locally, but I took your solution and put it into a fiddle so that some others later might have complete code that runs and they can play with.

https://dotnetfiddle.net/mAU6gi

Additionally this highlights the need to include, and has the nuget packages needed readily available on the page!

using Newtonsoft.Json;
using System.Collections.Generic;

This also then shows a user how to enumerate their new nested list and display all of the values in the order they came in from the JSON.

Thanks! -App-Devon

Comments

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.