Reputation: 33
I am trying to read in a JSON file using C# consisting of three fields: "name" and "ID", both strings, and "bitmask", which was written out from Python in the nested list format
[[0.0, 0.0], [1.0, 1.0], ...].
Reading the file and accessing the string fields is no problem, but I haven't been able to crack the "bitmask" field. Ultimately I want to be able to put the fields into a dictionary to process into a database later.
I am new to C#, so my approaches have been a bit naive. I attempted to cast it as a List<List<float>>
with no luck, as it appears you have to add each sublist iteratively. Is what I am trying to do even possible in C#? Here is my basic read-in code (taken from another extremely helpful post!).
I have access to the Python code that wrote out the JSONs, so if there is a different format for the lists that would make it possible to read in, I can re-process them.
using (StreamReader file = File.OpenText(@"C:\Users...\data2.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject)JToken.ReadFrom(reader);
string n = (string)o2.SelectToken("name");
Console.WriteLine("Name field from JSON: {0}", n);
Console.ReadKey();
}
Upvotes: 2
Views: 1020
Reputation: 129707
Casting a JToken
to a List<List<float>>
will not work because JToken
only has explicit conversion operators for simple values like string
, int
, bool
, double
, etc. (See here for the full list.) To convert a complex object you should use the ToObject
method instead:
var bitmask = o2["bitmask"].ToObject<List<List<float>>>();
Upvotes: 1