require_once
require_once

Reputation: 2045

Parsing JSON with different Token in .NET

I am getting a response from Klout API. The response has has the following fields

I had created classes in .NET and I populate the objects with JSON response. This is working fine but sometimes there is not ScoreDeltas in my JSON response. How I cam check this on spot?

JavaScriptSerializer _jsserializer = new JavaScriptSerializer();
var list = _jsserializer.Deserialize<List<KloutInfluencer>>(influencer as string);

//KloutInfluencer is the ckass with all fields.

It gives me NullReference at this

public double dayChange
{
    get { return entity.payload.scoreDeltas.dayChange ; }
}

This is because there is no ScoreDelta element in JSON response (for this id). How can I check that on runtime?

Upvotes: 1

Views: 188

Answers (2)

Sascha
Sascha

Reputation: 10347

Option 1 - Handle within your property:

You could write something like this:

public double dayChange
{
    get { return entity.payload.scoreDeltas == null ? 0 : entity.payload.scoreDeltas.dayChange }
}

Option 2 - Handle after deserialization manually for all objects:

Actually you would need to decide on a default value - this is probably acceptable. You might manually work through your list setting the scoreDeltas to a new instance. Something like this:

list.ForEach( entry => entry.scoreDeltas = entry.scoreDeltas ?? new ScoreDealtas() );
// On my MAC currently, untested, should show an idea

Option 3 - Handle directly after deserialization within each object:

Microsoft also provides you with an interface that you can implement that is called when an object was deserialized (IDeserializationCallback, http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ideserializationcallback.aspx). If you implement this in the KloutInfluencer class, you could handle properties that where left null because the json does not provided a value for.

Upvotes: 1

hangy
hangy

Reputation: 10859

You could change the dayChange property of the KloutInfluencer class to be nullable and just check if the scoreDeltas property of the payload is set.

public double? dayChange
{
    get
    {
        if (null == entity ||
            null == entity.payload ||
            null == entity.payload.scoreDeltas)
        {
            return null;
        }

        return entity.payload.scoreDeltas.dayChange;
    }
}

Upvotes: 1

Related Questions