简体   繁体   English

将数组的json数组反序列化为C#中的字符串列表

[英]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 .我想知道如何将json 数组的 json 数组转换(反序列化)为 string 列表

which means that inner array should be converted into string这意味着应将内部数组转换为字符串

the json is : json是:

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

the c# code using built-in c# json deserializer is :使用内置 c# json 反序列化器的 c# 代码是:

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

This exception occurs :发生此异常:

在此处输入图片说明

And Newtonsoft :和牛顿软件:

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

在此处输入图片说明

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.在我无法使用 dotnetcore 3.1 和 Newtonsoft 中的内置反序列化器反序列化这个 json (这是谷歌翻译 api 响应)之后,我决定将它手动转换为类和字符串,但我的代码不起作用。

the result should be like that :结果应该是这样的:

list :列表 :

item 1 :第 1 项:

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

item 2 :第 2 项:

[
        "d",
        "e",
        null,
        2
]
  1. Is there a way to deserialize the json I mentioned in the link into classes ?有没有办法将我在链接中提到的 json 反序列化为类? (Visual Studio Special Paste didn't work) (Visual Studio 特殊粘贴不起作用)

  2. Why I cannot convert json array of json array into List of string ?为什么我不能将 json 数组的 json 数组转换为字符串列表?

  3. Is this problem related with this issue ?与此相关的问题,这个问题

You have not only string in your collection and you have nested arrays, so List<string> does not represent your JSON structure.您的集合中不仅有字符串,而且还有嵌套数组,因此List<string>不代表您的 JSON 结构。 If you want to get only string you can do something like this (this one is with Newtonsoft, after fixing the d value):如果你只想得到字符串,你可以做这样的事情(这是在 Newtonsoft 中,在修复d值之后):

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.或者如果要将所有值转换为字符串,请在Select使用arr => arr.Select(a => a?.ToString()

Or you can convert to List<JArray> with Newtonsoft and call ToString on it:或者您可以使用 Newtonsoft 转换为List<JArray>并在其上调用ToString

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]"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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