Reputation: 625
Does anyone know how to convert a string which contains JSON into a c# 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, ... ]
]
Upvotes: 0
Views: 902
Reputation: 59637
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
Upvotes: 1
Reputation: 2761
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];
Upvotes: 0