Read json file into C# data structures?

Dec 16, 2009 at 6:00 PM

Experienced programmer but completely new to json and haven't been doing C# for very long either.

Have this:

StreamReader re = File.OpenText("url");
            JsonTextReader jsonReader = new JsonTextReader(re);
            // compiles but doesn't do what I want
            TTProject deserializedTTProject = JsonConvert.DeserializeObject(jsonReader.Read());

What I want to do (and it's not doing) is convert all of the file to a json string and then put this into data structures of type TTProject.

Also need to make TTProject an array.  Simply adding deserializedTTProject[] doesn't compile.  But then that doesn't entirely surprise me either.

No preview?  Well I'm not quite sure how this going to appear.  One can see this as html ... what does the <pre> tag do?  Ah, fixed width.  Whatever.

Dec 16, 2009 at 6:20 PM

Might add.


            while (jsonReader.Read())

does work.

Did this first as a double-check.  It means, for one, that my json file (disk file) is well-formed.

Dec 17, 2009 at 6:24 PM

Got it figured out and working.

After some further progress was then seeing: {"Could not cast or convert from System.String to System.String[]."}

In short, you need to make sure that when you indicate an array in C#, json has to have an array also (duh).

As in [ "one", "two" ]

I guess the real point is in battling through the phenomenology of it all so that you can eventually see it for what it is.


Dec 17, 2009 at 6:27 PM

Ah yes - question (in the event that anyone is listening).

I'll probably get this one figured out as well but it never hurts (well almost never) to ask.

I'm loading my json now into a series of 3 enveloping C# classes which are basically just strings or arrays of strings.  I imagine one can also load into a C# Dictionary as well?  (I'm new not just to json but C# also).  Presumably a C# Dictionary would make navigation easier.


Dec 17, 2009 at 6:58 PM

Yes. If you just want to access the JSON and don't care about what class you put it into then you could load it into a JObject which is basically a dictionary.

JObject o = JObject.Parse(jsonText);

Dec 21, 2009 at 9:10 PM

thanx James.  I'll give that a try.


Aug 11, 2010 at 8:46 PM
Is is possible to use JsonReader and read it directly into an object? I want to deserialize a JSON string without converting to a string... Is this possible? Thanks!
Aug 12, 2010 at 2:47 AM

Yes. JsonConvert.DeserializeObject is just a wrapper over JsonSerializer which uses a JsonReader.