简体   繁体   English

在C#中转换数组.. json的数组

[英]convert an array of array .. json in C#

given an apparently invalid json (which comes from google) 给定一个显然无效的json(来自Google)

https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=de&dt=t&q=Science https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=de&dt=t&q=科学

of

[[["Wissenschaft","Science",,,2]],,"en"]

i want to get the values of Wissenschaft and Science 我想获得维森夏夫特和科学的价值

if figured out a very inelegant way to do it with Json.net via 如果想出一种非常优雅的方式通过Json.net做到这一点

string h = "[[[\"Wissenschaft\",\"Science\",,,2]],,\"en\"] ";
var obj = JsonConvert.DeserializeObject<List<dynamic>>(h);
JArray arr1 = obj[0];
var arr2 = arr1.First;
var x = arr2.First.Next;
string s = x.ToString();

is there some better, less verbose way ? 有没有更好,更详细的方法?

Here is a more concise version, maybe somebody has one which also retains the other values from the top array 这是一个更简洁的版本,也许有人使用它也保留了顶部数组中的其他值

string h = "[[[\"Wissenschaft\",\"Science\",,,2]],,\"en\"]";
JsonSerializerSettings settings = new JsonSerializerSettings();
    settings.Error = (serializer, err) =>
    {
        err.ErrorContext.Handled = true;
        //ignore all errors   
    };
var obj = JsonConvert.DeserializeObject<List<List<List<dynamic>>>>(h,settings);
string strWissenschaft = obj[0][0][0];
string strScience = obj[0][0][1];

As you see i only care for the values in the most nested array, the other values are lost. 如您所见,我只关心最嵌套数组中的值,其他值丢失了。

For first this is not valid JSON object but nevermind as you said Json.NET will parse it by adding null values into empty commas. 首先,这不是有效的JSON对象,但是请记住,正如您所说的, Json.NET会通过将空值添加到空逗号来解析它。

Because this is not valid object and it is just an array in some JSON format. 因为这不是有效的对象,并且只是某种JSON格式的数组。 There will probably no better way then parse it into dynamic List as you already did. 像您已经做过的那样,可能没有更好的方法将其解析为动态List。

In case of { } at start and end and some keys:values format you can deserialize it into C# object according to class which you can define. 对于{ }开头和结尾以及某些key:values格式的情况,您可以根据可以定义的类将其反序列化为C#对象。

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

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