RealityDysfunction
RealityDysfunction

Reputation: 2639

Deserialize JSON string with variable number of elements

I am receiving a third party API JSON response through Javascript, which I AJAX send to the server. Here I am trying to convert this into an object. I've seen some simple example of this online using a custom class, but the problem in my case is that the number of fields can change. In one case they may just be: UserName: Blah, Age: Blah...In another case it may be: UserName: Blah, Age: Blah, Favourite game: Blah.

What is the best solution here?

Thank you for any input.

PS: I am trying this code below, but I get error: Friends is not supported for deserialization of an array.

public class Friends 
{
    public IList<IDictionary<string,string>>data {get;set;}
}

protected void UpdateTrigger_Click(object sender, EventArgs e)
{
    Friends fbFriends = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Friends>(Hidden1.Value);
}

Upvotes: 4

Views: 316

Answers (1)

Trevor Pilley
Trevor Pilley

Reputation: 16393

Use Json.NET - you can deserialise into a custom .NET object that exposes all the properties and do if (thing.Property != null) to get the specific values, or you could deserialise to dynamic.

Upvotes: 3

Related Questions