Al.
Al.

Reputation: 875

How to handle json object in codebehind

I have - var JsonObj = []; and I pushed some data into that and send it to codebehind using JQuery.ajax() method. I am able to receive in a method which has parameter like this

[WebMethod]
public static void SaveInfo(List<Object> userEnteredDetails)
{
}

And i loop thru the collection to get the data something like this,

foreach (object item in userEnteredDetails)
{
Dictionary<string, object> details = item as  Dictionary<string, object>;

string name = details["customerName"] as string;
}

The problem here is, I am receiving more than 10 items in the collecton. So i cannot read another property in my above for loop. Something like this,

foreach (object item in userEnteredDetails)
{
Dictionary<string, object> details = item as  Dictionary<string, object>;

string name = details["customerName"] as string;
string city= details["city"] as string;
}

Firsttime city wil throw an error, and next time customername. Because item variable will have one variable at a time. How to read all the more than 10 records efficiently since we dont have property, but can read only through an indexer (details["customerName"]).

Upvotes: 2

Views: 1877

Answers (4)

Christian Phillips
Christian Phillips

Reputation: 18759

Theres a very flexible json framework (JSON.NET) which could help with this, definitley worth considering if your doing a lot of work with JSON http://json.codeplex.com/

Upvotes: 1

Tomas Grosup
Tomas Grosup

Reputation: 6514

You can enumerate the details Dictionary.

foreach(var kvp in details)
  {
// do something with kvp.Key and kvp.Value
  }

EDIT: To get a one merged details dictionairy first, you can try this:

var details = list.Select(item => item as Dictionary<string, object>).SelectMany(d => d).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

Upvotes: 2

Kapil Khandelwal
Kapil Khandelwal

Reputation: 16144

Try this:

string name = String.Empty;
string city = String.Empty;
foreach (object item in userEnteredDetails)
{
 Dictionary<string, object> details = item as  Dictionary<string, object>;
if (details.ContainsKey("customerName"))
 name = details["customerName"] as string;
if (details.ContainsKey("city"))
 city= details["city"] as string;
}

Upvotes: 3

Vinoth
Vinoth

Reputation: 2439

One thing you could have a type with fields in them mapping to the list of objects. While making the ajax call stringify the json object. In your web method recieve it as string. Use Json Deserializer and deserialize it to the type you have created.

Upvotes: 1

Related Questions