简体   繁体   中英

convert an array of array .. json in C#

given an apparently invalid json (which comes from google)

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

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

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.

Because this is not valid object and it is just an array in some JSON format. There will probably no better way then parse it into dynamic List as you already did.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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