Solved

Deserialize

Posted on 2013-11-11
18
577 Views
Last Modified: 2014-03-18
Hi,

I need to deserialize the following JSON code that comes to a specified url on my asp.net website (I'm using vb.net). The serialized code I would like to add to an object so I can add each element to the database.

[{"email":"john.doe@sendgrid.com","timestamp":1337197600,"smtp-id":"<4FB4041F.6080505@sendgrid.com>","event":"processed"},{"email":"john.doe@sendgrid.com","timestamp":1337966815,"smtp-id":"<4FBFC0DD.5040601@sendgrid.com>","category":"newuser","event":"processed"},{"email":"john.doe@sendgrid.com","timestamp":1337969592,"smtp-id":"<20120525181309.C1A9B40405B3@Mohammeds-Mac.local>","event":"processed"},{"email":"bill.nye@thescienceguy.com","timestamp":1337971272,"smtp-id":"<20120525184109.9578F40409A5@Mohammeds-Mac.local>","reason":"Unsubscribed Address","event":"dropped"},{"email":"bill.nye@thescienceguy.com","timestamp":1337979680,"smtp-id":"<20120525210118.7F3724041B6D@Mohammeds-Mac.local>","reason":"Unsubscribed Address","event":"dropped"},{"email":"bill.nye@thescienceguy.com","timestamp":1337980426,"smtp-id":"<20120525211344.2844C4041EB2@Mohammeds-Mac.local>","reason":"Unsubscribed Address","event":"dropped"},{"email":"iamemail@gmail.com","attempt":"17","smtp-id":"<4FB29F5D.5080404@sendgrid.com>","timestamp":1337201407,"response":"501 Syntax error - Badly formatted address. ","event":"deferred"},{"email":"iamemail@gmail.com","attempt":"18","smtp-id":"<4FB29F5D.5080404@sendgrid.com>","timestamp":1337212247,"response":"Connection timed out","event":"deferred"},{"email":"iamemail@gmail.com","attempt":"25","smtp-id":"<4FB29F5D.5080404@sendgrid.com>","timestamp":1337288707,"response":"501 Syntax error - Badly formatted address. ","event":"deferred"},{"email":"john.doe@sendgrid.com","smtp-id":"<4FBFC0DD.5040601@sendgrid.com>","timestamp":1337966817,"response":"250 2.0.0 OK 1337966817 z9si3846029icy.10 ","category":"newuser","event":"delivered"},{"email":"john.doe@sendgrid.com","smtp-id":"<20120525183816.12AA6404092A@Mohammeds-Mac.local>","timestamp":1337971099,"response":"250 2.0.0 OK 1337971099 l10si4052001icz.31 ","event":"delivered"},{"email":"foobar@yahoo.com","smtp-id":"<20120525183951.59BEA4040968@Mohammeds-Mac.local>","timestamp":1337971198,"response":"250 2.0.0 OK 1337971198 xz10si2239282obb.108 ","event":"delivered"},{"email":"foobar@yahoo.com","smtp-id":"<20120525181029.220EE404043A@Mohammeds-Mac.local>","timestamp":1337969434,"status":"5.1.1","reason":"550 5.1.1 The email account that you tried to reach does not exist. Please try double-checking the recipient's email address for typos or unnecessary spaces. Learn more at http://support.google.com/mail/bin/answer.py?answer=6596 z6si25868142igk.15 ","type":"bounce","event":"bounce"},{"email":"john.doe@sendgrid.com","timestamp":1338574236,"url":"http://www.sendgrid.com","event":"click"},{"email":"john.doe@sendgrid.com","timestamp":1338572978,"url":"http://www.sendgrid.com","event":"click"},{"email":"john.doe@sendgrid.com","timestamp":1338595596,"url":"http://www.sendgrid.com","event":"click"},{"email":"john.doe@sendgrid.com","timestamp":1338312226,"newsletter":{"newsletter_user_list_id":"1695412","newsletter_id":"310318","newsletter_send_id":"425605"},"category":["dsfdsf","Newsletter"],"event":"open"},{"email":"john.doe@sendgrid.com","timestamp":1338487320,"event":"open"},{"email":"john.doe@sendgrid.com","timestamp":1338578578,"event":"open"},{"email":"john.doe@sendgrid.com","timestamp":1340126539,"newsletter":{"newsletter_user_list_id":"1695412","newsletter_send_id":"478915","newsletter_id":"428128"},"category":["TESTt","Newsletter"],"event":"unsubscribe"},{"email":"john.doe@sendgrid.com","timestamp":1338310756,"newsletter":{"newsletter_user_list_id":"1695100","newsletter_send_id":"425584","newsletter_id":"331537"},"category":["TEST","Newsletter"],"event":"unsubscribe"},{"email":"john.doe@sendgrid.com","timestamp":1340126539,"newsletter":{"newsletter_user_list_id":"1695412","newsletter_send_id":"478915","newsletter_id":"428128"},"category":["TESTt","Newsletter"],"event":"unsubscribe"},{"email":"mysendgriid@hotmail.com","event":"spamreport","timestamp":1347307636,"category":["board_collaborator_new_pin"],"unique_args":{"tracking_id":"c99z72cd5537515d9b0e3d8cab1ec09e","time_sent":1346814447,"sender_username":"notasendr","recipient_username":"realusername"}}]

Open in new window


Is there any of you experts that can show me how to accomplish this?!

Thanks for help!

Peter
0
Comment
Question by:peternordberg
  • 10
  • 7
18 Comments
 
LVL 45

Expert Comment

by:aikimark
ID: 39640908
If performance is an issue, I would recommend the fastJSON code from Mehdi Gholam:
http://fastjson.codeplex.com/

Author's description of the project and performance comparisons to other JSON deserializing functions/methods/libraries.
http://www.codeproject.com/Articles/159450/fastJSON
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 39641497
Here a class that you can use with NewtonSoft JSON serializer:

// Generated by Xamasoft JSON Class Generator
// http://www.xamasoft.com/json-class-generator

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Example
{

    public class Request
    {

        public class Newsletter2
        {

            [JsonProperty("newsletter_user_list_id")]
            public string NewsletterUserListId { get; set; }

            [JsonProperty("newsletter_id")]
            public string NewsletterId { get; set; }

            [JsonProperty("newsletter_send_id")]
            public string NewsletterSendId { get; set; }
        }

        public class UniqueArgs
        {

            [JsonProperty("tracking_id")]
            public string TrackingId { get; set; }

            [JsonProperty("time_sent")]
            public int TimeSent { get; set; }

            [JsonProperty("sender_username")]
            public string SenderUsername { get; set; }

            [JsonProperty("recipient_username")]
            public string RecipientUsername { get; set; }
        }


        [JsonProperty("email")]
        public string Email { get; set; }

        [JsonProperty("timestamp")]
        public int Timestamp { get; set; }

        [JsonProperty("smtp-id")]
        public string SmtpId { get; set; }

        [JsonProperty("event")]
        public string Event { get; set; }

        [JsonProperty("category")]
        public object Category { get; set; }

        [JsonProperty("reason")]
        public string Reason { get; set; }

        [JsonProperty("attempt")]
        public string Attempt { get; set; }

        [JsonProperty("response")]
        public string Response { get; set; }

        [JsonProperty("status")]
        public string Status { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("url")]
        public string Url { get; set; }

        [JsonProperty("newsletter")]
        public Newsletter2 Newsletter { get; set; }

        [JsonProperty("unique_args")]
        public UniqueArgs UniqueArgs { get; set; }

    }
}

Open in new window

0
 

Author Comment

by:peternordberg
ID: 39642421
Hi and thanks so much for the code example,

How do I get the dll files for that library (saw it on Github, but do I need to download some special part?).

How do I actually bring in the url response to my class?

Thanks so much for your help!

Peter
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 39642435
You can install NewtonSoft from Nuget:

Json.NET 5.0.8
http://www.nuget.org/packages/newtonsoft.json/
0
 

Author Comment

by:peternordberg
ID: 39642444
Hi and thanks,

Did you see my other question?

Peter
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 39642452
How do I actually bring in the url response to my class?
I would need more context before I could suggest something.  

What kind of application are you working with?  

How do you get the response?
0
 

Author Comment

by:peternordberg
ID: 39642464
asp.net site with vb.net
this is a description of the post:


Peter
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 39642474
Description missing...
0
 

Author Comment

by:peternordberg
ID: 39642486
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 96

Expert Comment

by:Bob Learned
ID: 39642512
It sounds like when SendGrid sends an email for you, that you get a notification as a post to a URL.

If you have a standard Web Forms ASP.NET web site, then you can read the post in the Page_Load event handler.  

Dim userName As String = Request.Form("UserName")
Dim password As String = Request.Form("Password")

Open in new window


If it is a different type of web site, then I would need to know what you are working with.
0
 

Author Comment

by:peternordberg
ID: 39642651
Hi,

They say it's an  HTTP Posts in JSON format. Can that be retrieved the way you described above?

Peter
0
 

Author Comment

by:peternordberg
ID: 39642659
it's sent to an url specified for example http://mysite.com/webhook.aspx. But then I need to desirialize it.

Peter
0
 

Author Comment

by:peternordberg
ID: 39642711
I can test to post to an url and then I get this example for what is posted:

JSON post
The JSON data posted is like this:
[{"email":"john.doe@sendgrid.com","timestamp":1337197600,"smtp-id":"<4FB4041F.6080505@sendgrid.com>","event":"processed"},{"email":"john.doe@sendgrid.com","timestamp":1337966815,"smtp-id":"<4FBFC0DD.5040601@sendgrid.com>","category":"newuser","event":"processed"},{"email":"john.doe@sendgrid.com","timestamp":1337969592,"smtp-id":"<20120525181309.C1A9B40405B3@Mohammeds-Mac.local>","event":"processed"},{"email":"bill.nye@thescienceguy.com","timestamp":1337971272,"smtp-id":"<20120525184109.9578F40409A5@Mohammeds-Mac.local>","reason":"Unsubscribed Address","event":"dropped"},{"email":"bill.nye@thescienceguy.com","timestamp":1337979680,"smtp-id":"<20120525210118.7F3724041B6D@Mohammeds-Mac.local>","reason":"Unsubscribed Address","event":"dropped"},{"email":"bill.nye@thescienceguy.com","timestamp":1337980426,"smtp-id":"<20120525211344.2844C4041EB2@Mohammeds-Mac.local>","reason":"Unsubscribed Address","event":"dropped"},{"email":"iamemail@gmail.com","attempt":"17","smtp-id":"<4FB29F5D.5080404@sendgrid.com>","timestamp":1337201407,"response":"501 Syntax error - Badly formatted address. ","event":"deferred"},{"email":"iamemail@gmail.com","attempt":"18","smtp-id":"<4FB29F5D.5080404@sendgrid.com>","timestamp":1337212247,"response":"Connection timed out","event":"deferred"},{"email":"iamemail@gmail.com","attempt":"25","smtp-id":"<4FB29F5D.5080404@sendgrid.com>","timestamp":1337288707,"response":"501 Syntax error - Badly formatted address. ","event":"deferred"},{"email":"john.doe@sendgrid.com","smtp-id":"<4FBFC0DD.5040601@sendgrid.com>","timestamp":1337966817,"response":"250 2.0.0 OK 1337966817 z9si3846029icy.10 ","category":"newuser","event":"delivered"},{"email":"john.doe@sendgrid.com","smtp-id":"<20120525183816.12AA6404092A@Mohammeds-Mac.local>","timestamp":1337971099,"response":"250 2.0.0 OK 1337971099 l10si4052001icz.31 ","event":"delivered"},{"email":"foobar@yahoo.com","smtp-id":"<20120525183951.59BEA4040968@Mohammeds-Mac.local>","timestamp":1337971198,"response":"250 2.0.0 OK 1337971198 xz10si2239282obb.108 ","event":"delivered"},{"email":"foobar@yahoo.com","smtp-id":"<20120525181029.220EE404043A@Mohammeds-Mac.local>","timestamp":1337969434,"status":"5.1.1","reason":"550 5.1.1 The email account that you tried to reach does not exist. Please try double-checking the recipient's email address for typos or unnecessary spaces. Learn more at http://support.google.com/mail/bin/answer.py?answer=6596 z6si25868142igk.15 ","type":"bounce","event":"bounce"},{"email":"john.doe@sendgrid.com","timestamp":1338574236,"url":"http://www.sendgrid.com","event":"click"},{"email":"john.doe@sendgrid.com","timestamp":1338572978,"url":"http://www.sendgrid.com","event":"click"},{"email":"john.doe@sendgrid.com","timestamp":1338595596,"url":"http://www.sendgrid.com","event":"click"},{"email":"john.doe@sendgrid.com","timestamp":1338312226,"newsletter":{"newsletter_user_list_id":"1695412","newsletter_id":"310318","newsletter_send_id":"425605"},"category":["dsfdsf","Newsletter"],"event":"open"},{"email":"john.doe@sendgrid.com","timestamp":1338487320,"event":"open"},{"email":"john.doe@sendgrid.com","timestamp":1338578578,"event":"open"},{"email":"john.doe@sendgrid.com","timestamp":1340126539,"newsletter":{"newsletter_user_list_id":"1695412","newsletter_send_id":"478915","newsletter_id":"428128"},"category":["TESTt","Newsletter"],"event":"unsubscribe"},{"email":"john.doe@sendgrid.com","timestamp":1338310756,"newsletter":{"newsletter_user_list_id":"1695100","newsletter_send_id":"425584","newsletter_id":"331537"},"category":["TEST","Newsletter"],"event":"unsubscribe"},{"email":"john.doe@sendgrid.com","timestamp":1340126539,"newsletter":{"newsletter_user_list_id":"1695412","newsletter_send_id":"478915","newsletter_id":"428128"},"category":["TESTt","Newsletter"],"event":"unsubscribe"},{"email":"mysendgriid@hotmail.com","event":"spamreport","timestamp":1347307636,"category":["board_collaborator_new_pin"],"unique_args":{"tracking_id":"c99z72cd5537515d9b0e3d8cab1ec09e","time_sent":1346814447,"sender_username":"notasendr","recipient_username":"realusername"}}]

Open in new window

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 39642742
In the Webhook.aspx, you should be able to get posted JSON, but you need to know the key.  One possible way to discover that is to put a breakpoint in the Page_Load, and examine the Request.Form keys.  Another way is to use an HTTP debugger, like Fiddler.
0
 

Author Comment

by:peternordberg
ID: 39642805
On their page they said I can test the post by using this command:
curl -X POST -H "Content-Type: application/json" -d '[{"email":"john.doe@sendgrid.com","timestamp":1337197600,"smtp-id":"<4FB4041F.6080505@sendgrid.com>","event":"processed"},{"email":"john.doe@sendgrid.com","timestamp":1337966815,"smtp-id":"<4FBFC0DD.5040601@sendgrid.com>","category":"newuser","event":"clicked"},{"email":"john.doe@sendgrid.com","timestamp":1337969592,"smtp-id":"<20120525181309.C1A9B40405B3@Example-Mac.local>","event":"processed"}]'

Open in new window


Does that say something to you?

Peter
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 39642827
CURL is a utility that you can download:

http://curl.haxx.se/download.html

It can simulate the JSON post from their service.
0
 

Author Comment

by:peternordberg
ID: 39692141
Hi,

Exuse me for not being active on this thread. I had to turn my attention to another acute problem. However, I have not been able to solve this yet. There is no "key" to get from this JSON response and I don't really know how to be able to see what data is sent to be so that I can begin to work with it.

Peter
0
 

Author Comment

by:peternordberg
ID: 39711429
Hi,

I've come this far in trying to get hold of the json post but I can't get it to work. Anyone that can give me some more direction on how to manage?!

 Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
          

            Request.InputStream.Position = 0 'you need this else the magic doesn't happen
            Dim inputStream As New StreamReader(Request.InputStream)
            Dim json As String = inputStream.ReadToEnd()

            'Dim nl As New Sendgrid
            Dim jss As New System.Web.Script.Serialization.JavaScriptSerializer()
            Dim dict As Dictionary(Of String, String) = jss.Deserialize(Of Dictionary(Of String, String))(json)
            'We're telling it with the String, String to expect both the name of the value and the value as strings.
            For Each item As KeyValuePair(Of String, String) In dict
                Response.Write(item.Key & " - " & item.Value & "<br>")
                If dict.ContainsKey("email") Then
                    'nl.Email = dict("email")
                    Insert(dict("email"))
                End If
            Next

            'Dim nl As SendgridJsonConvert.DeserializeObject(Of Sendgrid)(json)
            'Dim dict As Dictionary(Of String, String) =
            'Response.Write(nl.Email)


        End If
    End Sub


    Public Sub Insert(email As String)
        Dim dbConn As New SqlConnection(config.ConnectionString)
        Dim sqlString As String
        sqlString = "INSERT INTO testSendgrid (email) VALUES (@email)"

        Dim sqlCmd As New SqlCommand(sqlString, dbConn)
        sqlCmd.CommandType = CommandType.Text

        sqlCmd.Parameters.AddWithValue("@email", email)

        Try

            dbConn.Open()

            sqlCmd.ExecuteNonQuery()

        Finally
            dbConn.Close()
            sqlCmd = Nothing
            dbConn = Nothing
        End Try

    End Sub

Open in new window

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now