简体   繁体   中英

convert json string into two dimensional bool array

Does anyone know how to convert a string which contains JSON into ac# 2D array. I have this which reads the text/json from a web Browser and stores it into a string.

 "BoolArry": [
               [ true, true, false, ... ],
               [ true, true, true, ...],
               ...,
               [ true, false, false, ... ]
             ]

You can use the JavaScript serializer provided by .Net: JavaScriptSerializer (use using System.Web.Script.Serialization; )

var boolArrayStr =
    @"[
        [ true, true, true ],
        [ true, true, false ],
        [ true, false, false ],
        [ false, false, false ],
    ]";

JavaScriptSerializer jss = new JavaScriptSerializer();

bool[][] boolArrays = jss.Deserialize<bool[][]>(boolArrayStr);

foreach (bool[] array in boolArrays)
{
    foreach (bool val in array)
    {
        Console.Write(val);
        Console.Write(" ");
    }

    Console.WriteLine("");
}

Output is:

True True True
True True False
True False False
False False False

I wrote Json to file (D:\\Temp\\text.txt):

[
  [ true, true, false ],
  [ true, true, true ],
  [ true, false, false ]
]

You can read this as Newtonsoft.Json.Linq.JArray and convert as you wish:

Newtonsoft.Json.Linq.JArray obj = Newtonsoft.Json.JsonConvert.DeserializeObject(File.ReadAllText(@"D:\Temp\text.txt")) as Newtonsoft.Json.Linq.JArray;
var arr = (from e in obj select e.Values<bool>().ToArray()).ToArray();

arr is of type bool[][] (array of arrays)

Usage:

bool value = arr[x][y];

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