-2

I mostly work on the PHP , recently have switched to ASP.NET,

When parse the JSON, I can simply use -> to get the field, e.g.

foreach(json_decode($_POST['mandrill_events']) as $event) {
    $event = $event->event;
    $email_type = $event->msg->metadata->email_type;
}

However, in ASP.NET , there is no action, this is my attempt code

var post_data =  Request.Form["mandrill_events"];

JavaScriptSerializer ser = new JavaScriptSerializer();
var post_data_json = ser.Deserialize<Dictionary<string, string>>(post_data);

foreach (var event_obj in post_data_json) {
   //how to parse the event_obj?
}

Thanks a lot for helping.

Divyang Desai
  • 7,483
  • 13
  • 50
  • 76
user782104
  • 13,233
  • 55
  • 172
  • 312

2 Answers2

2

use Newtonsoft Json.NET

JsonConvert.DeserializeObject<DataModel>(json);
M. Wiśnicki
  • 6,094
  • 3
  • 23
  • 28
1

Unless you want to write a C# class that represents the JSON you are POSTing (the safest solution), you can use the dynamic type to create an object which will look like your JSON. You can then do something like this answer to access the properties.

This solution doesn't give you type safety and the DLR will resolve the properties of the dynamic object at runtime.

As other answers have mentioned, your life will be made much easier by using Newtonsoft JSON which will allow you to write:

dynamic events = JsonConvert.DeserializeObject<dynamic>(post_data);

foreach(dynamic evt in events)
{
    string emailType = evt.msg.metadata.email_type;
}
Community
  • 1
  • 1
Dan Def
  • 1,836
  • 2
  • 21
  • 39