0

I am trying to read json from a local .json file and parse the contents using StreamReader and Json.NET. Json & my code:

contents of .json file: {"rate":50,"information":{"height":70,"ssn":43,"name":"andrew"}}

                using (var sr = new StreamReader(pathToJsonFile))
                {
                    dynamic jsonArray = JsonConvert.DeserializeObject(sr.ReadToEnd());
                    foreach(var item in jsonArray)
                    {
                       Console.WriteLine(item.rate);
                       Console.WriteLine(item.ssn);
                    }
                }

This gives me an error on the line foreach(var item in array): Object reference not set to an instance of an object. I am guessing this is because my json is not actually an array but that is how I am trying to parse it. How can I parse this json in order to pull out fields such as rate or ssn?

NB - please do not flag this question as a duplicate of Read and parse a Json File in C#, as that is where I got my original code from.

EDIT: As has been pointed out in other answers, jsonArray is null. That explains my error but still does not answer my question. How else can I parse this json in order to extract the desired fields?

Community
  • 1
  • 1
user3772119
  • 484
  • 3
  • 7
  • 16
  • Are you sure about the content of json file? the name andrew is not wrapped in (") – K D Jul 09 '14 at 15:28
  • It should be. Sorry, I have edited the post. Thanks for pointing out that mistake. – user3772119 Jul 09 '14 at 15:29
  • Also as it is not an array, try to access the object property directly first – K D Jul 09 '14 at 15:35
  • I would rather suggest to change your code first and remove the foreach loop. and try to access your values using **jsonArray.rate** – K D Jul 09 '14 at 15:50

7 Answers7

1

In any case, I would check for null (DeserializeObject can obviously return null):

        using (var sr = new StreamReader(pathToJsonFile))
        {
            dynamic jsonArray = JsonConvert.DeserializeObject(sr.ReadToEnd());
            if(jsonArray != null) //new check here
            {
               foreach(var item in jsonArray)
               {
                  Console.WriteLine(item.rate);
                  Console.WriteLine(item.ssn);
               }
            }
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70
  • Okay, so I just tried that and the `jsonArray` *is* null. However, that does not answer my question: "How can I parse this json in order to pull out fields such as `rate` or `ssn`?" – user3772119 Jul 09 '14 at 15:33
1

I am guessing this is because my json is not actually an array

True, the returned object is dynamic, so make use of dynamic:

var json = "{\"rate\":50,\"information\":{\"height\":70,\"ssn\":43,\"name\":\"andrew\"}}";
dynamic obj = JsonConvert.DeserializeObject(json);


Console.WriteLine("rate: {0}. ssn: {1}", obj.rate, obj.information.ssn);

See live sample here: https://dotnetfiddle.net/nQYuyX

Max Yakimets
  • 1,195
  • 7
  • 12
1

A couple things:

If you want to manually parse out the values, you should try using JObject rather than JsonConvert.DeserializeObject. The following code should work:

            dynamic jsonObject = JObject.Parse("{'rate':50,'information':{'height':70,'ssn':43,'name':'andrew'}}");

            Console.WriteLine(jsonObject["rate"]);
            Console.WriteLine(jsonObject["information"]["ssn"]);

However, if you know how the json is structured, you should create a .net class like:

public class Person
{
    public int rate {get;set;}
    public Information information {get;set;}
}

public class Information
{
    public int height {get;set;}
    public int ssn {get;set;}
    public string name {get;set;}
}

and then use:

var person = JsonConvert.DeserializeObject<Person>(thestringtodeserialize);

That way you can have a strongly typed object.

codechinchilla
  • 2,129
  • 13
  • 23
  • On the former of your two examples, I get the exception: `Error reading JObject from JsonReader.Path ", line 0, position 0.` – user3772119 Jul 09 '14 at 16:10
  • user3772119 hmm, I just tried running it again and seems to work for me - I'm using a simple console app with the latest Json.NET from nuget - can you post the code you're running? – codechinchilla Jul 09 '14 at 16:23
  • The following code works for me, please make sure the json in the file is exactly: {"rate":50,"information":{"height":70,"ssn":43,"name":"andrew"}} `var pathtoJsonFile = @"c:\json.txt"; using (var sr = new StreamReader(pathtoJsonFile)) { dynamic jsonObject = JObject.Parse(sr.ReadToEnd()); Console.WriteLine(jsonObject["rate"]); Console.WriteLine(jsonObject["information"]["ssn"]); }` – codechinchilla Jul 09 '14 at 16:27
1

Are you sure it's an array? If that's the format the you expect from Json, maybe you should consider defining a class. For example:

    class SomeJsonObject
    {
        public int rate {get;set;}

        [JsonProperty("information")] //if you want to name your property something else
        public InformationObject Information {get;set;}
    }

    class InformationObject 
    {
        [JsonProperty("height", NullValueHandling = NullValueHandling.Ignore)] //some other things you can do with Json
        public int Height {get;set;}
        public int ssn {get;set;}
        public string name {get;set;}
    }

This way you can just deserialize it to an object:

    SomeJsonObject jsonArray = JsonConvert.DeserializeObject<SomeJsonObject>(sr.ReadToEnd());
Alkasai
  • 3,757
  • 1
  • 19
  • 25
0

i would fire up nuget and get the JSON.net package

https://www.nuget.org/packages/Newtonsoft.Json/

http://james.newtonking.com/json

it is well documented and can save you a tonne of work.

see also http://json2csharp.com/

EDIT: you are already using this

RoughPlace
  • 1,111
  • 1
  • 13
  • 23
  • Pretty sure OP is already using JSON.Net, with `JsonConvert.DeserializeObject` being a method in the library. And fyi, Json2CSharp is not written by the same developer. – JW Lim Jul 09 '14 at 15:39
0

I think your question is similar to this Deserialize JSON with C# . you can use JavaScriptSerializer

Community
  • 1
  • 1
Feras Salim
  • 438
  • 7
  • 33
0

I don't get a null reference (with Json.net 6.0.3) but your code has one obvious bug:

static void Main(string[] args) { string s = "{'rate':50,'information':{'height':70,'ssn':43,'name':'andrew'}}".Replace('\'', '\"'); var obj = JsonConvert.DeserializeObject(s); dynamic jsonArray = obj; foreach (var item in jsonArray) { Console.WriteLine(item.rate); Console.WriteLine(item.ssn); } }

The bug is Console.WriteLine(item.rate) will throw. Your 'array' jsonArray is not actually an array, it is a dictionary! Therefore, item=the first Key-Value-pair in the dictionary, = {"rate":50}. You can prevent the code from throwing by getting rid of your foreach loop.

Tim Lovell-Smith
  • 15,310
  • 14
  • 76
  • 93