Search code examples
c#jsonjson.netdeserializationjson-deserialization

Deserialize json array of array to List of string in C#


I want to know how can I convert(Deserialize) a json array of json array to a list of string.

which means that inner array should be converted into string

the json is :

[
      [
         "a",
         "b",
         "c",
         null,
         1
      ],
      [
         "d",
         "e",
         null,
         2
      ]
]

the c# code using built-in c# json deserializer is :

List<string> myList = System.Text.Json.JsonSerializer.Deserialize<List<string>>(json);

This exception occurs :

enter image description here

And Newtonsoft :

List<string> myList = JsonConvert.DeserializeObject<List<string>>(json);

enter image description here

After I couldn't deserialize this json (which is google translate api response) with built-in deserializer in dotnetcore 3.1 and Newtonsoft , I decided to convert it manually to classes and strings but my code didn't work.

the result should be like that :

list :

item 1 :

[
        "a",
        "b",
        "c",
        null,
        1
]

item 2 :

[
        "d",
        "e",
        null,
        2
]
  1. Is there a way to deserialize the json I mentioned in the link into classes ? (Visual Studio Special Paste didn't work)

  2. Why I cannot convert json array of json array into List of string ?

  3. Is this problem related with this issue ?


Solution

  • You have not only string in your collection and you have nested arrays, so List<string> does not represent your JSON structure. If you want to get only string you can do something like this (this one is with Newtonsoft, after fixing the d value):

    var strings = JsonConvert.DeserializeObject<List<List<object>>>(json)
        .Select(arr => arr.OfType<string>().ToList())
        .ToList();
    

    Or using arr => arr.Select(a => a?.ToString() in Select if you want to convert all values to strings.

    Or you can convert to List<JArray> with Newtonsoft and call ToString on it:

    List<string> strings = JsonConvert.DeserializeObject<List<JArray>>(json)
        .Select(jarr => jarr.ToString(Newtonsoft.Json.Formatting.None)) 
        .ToList();
    Console.WriteLine(string.Join(", ", strings)); // prints "["a","b","c",null,1], ["d","e",null,2]"