Deserialize JSON and put in object

Hi,

I need to deserialize this JSON string and put the values in properties so that I can use it in my asp.net application. How can I do it?

[{
"email": "example@domain.none",
"timestamp": 1386695691,
"smtp-id": "<9b9f3ef952a66d57f5d995ae5969d389@swift.generated>",
"sg_event_id": "g_WdqUa0QRat0oHRS_HRlw",
"sg_message_id": "142dd810965.1c18.18bd41.filterdell-005.2437.52A74C0A8.0",
"event": "processed"
}, {
"email": "example@domain.none",
"smtp-id": "<9b9f3ef952a66d57f5d995ae5969d389@swift.generated>",
"timestamp": 1386695693,
"response": "250 2.0.0 OK 1386695693 sw1si11026220pbc.12 - gsmtp ",
"sg_event_id": "ODCueMfYSFWkXWixpIi62Q",
"event": "delivered"
}, {
"email": "example@domain.none",
"timestamp": 1386695713,
"ip": "66.249.84.39",
"useragent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7 (via ggpht.com)",
"event": "open"
}, {
"email": "example@domain.none",
"smtp-id": "<142dd86a4be.197c.205564@localhost.localdomain>",
"timestamp": 1386696059,
"response": "250 2.0.0 OK 1386696059 ku6si10984836pbc.336 - gsmtp ",
"sg_event_id": "vwyR1ZoPQ06lnyOrbOIQWA",
"event": "delivered"
}, {
"email": "example@domain.none",
"timestamp": 1386696071,
"ip": "12.345.67.89",
"useragent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7 (via ggpht.com)",
"event": "open"
}, {
"email": "example@domain.none",
"timestamp": 1386696058,
"smtp-id": "<142dd86a4be.197c.205564@localhost.localdomain>",
"sg_event_id": "IW2rrBkQSJys2Fw0zNuuEg",
"sg_message_id": "142dd86a4be.197c.205564.filterdell-006.16119.52A74D7A2.0",
"event": "processed"
}] 

Open in new window


Thanks for help!

Peter
Peter NordbergIT ManagerAsked:
Who is Participating?
 
käµfm³d 👽Connect With a Mentor Commented:
OK, your JSON is a slightly different than what I've been working with lately, so the approach that I am accustomed to--what I showed you above--needs a slight tweak. You simply need to use the genericized version of the method:

Dim instance As List(Of LogItem) = JsonConvert.DeserializeObject(Of List(Of LogItem))(jsonString)

Open in new window


e.g.

Imports System.Runtime.Serialization
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Module Module1

    Sub Main()
        Dim jsonString As String = Module1.JSON()
        Dim instance As List(Of LogItem) = JsonConvert.DeserializeObject(Of List(Of LogItem))(jsonString)
    End Sub

    Function JSON() As String
        Return "[{" & _
"""email"": ""example@domain.none""," & _
"""timestamp"": 1386695691," & _
"""smtp-id"": ""<9b9f3ef952a66d57f5d995ae5969d389@swift.generated>""," & _
"""sg_event_id"": ""g_WdqUa0QRat0oHRS_HRlw""," & _
"""sg_message_id"": ""142dd810965.1c18.18bd41.filterdell-005.2437.52A74C0A8.0""," & _
"""event"": ""processed""" & _
"}, {" & _
"""email"": ""example@domain.none""," & _
"""smtp-id"": ""<9b9f3ef952a66d57f5d995ae5969d389@swift.generated>""," & _
"""timestamp"": 1386695693," & _
"""response"": ""250 2.0.0 OK 1386695693 sw1si11026220pbc.12 - gsmtp ""," & _
"""sg_event_id"": ""ODCueMfYSFWkXWixpIi62Q""," & _
"""event"": ""delivered""" & _
"}, {" & _
"""email"": ""example@domain.none""," & _
"""timestamp"": 1386695713," & _
"""ip"": ""66.249.84.39""," & _
"""useragent"": ""Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7 (via ggpht.com)""," & _
"""event"": ""open""" & _
"}, {" & _
"""email"": ""example@domain.none""," & _
"""smtp-id"": ""<142dd86a4be.197c.205564@localhost.localdomain>""," & _
"""timestamp"": 1386696059," & _
"""response"": ""250 2.0.0 OK 1386696059 ku6si10984836pbc.336 - gsmtp ""," & _
"""sg_event_id"": ""vwyR1ZoPQ06lnyOrbOIQWA""," & _
"""event"": ""delivered""" & _
"}, {" & _
"""email"": ""example@domain.none""," & _
"""timestamp"": 1386696071," & _
"""ip"": ""12.345.67.89""," & _
"""useragent"": ""Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7 (via ggpht.com)""," & _
"""event"": ""open""" & _
"}, {" & _
"""email"": ""example@domain.none""," & _
"""timestamp"": 1386696058," & _
"""smtp-id"": ""<142dd86a4be.197c.205564@localhost.localdomain>""," & _
"""sg_event_id"": ""IW2rrBkQSJys2Fw0zNuuEg""," & _
"""sg_message_id"": ""142dd86a4be.197c.205564.filterdell-006.16119.52A74D7A2.0""," & _
"""event"": ""processed""" & _
"" & _
"}] "
    End Function
End Module



<DataContract>
Public Class LogItem
    <DataMember(Name:="email")> _
    Public Property Email As String
    <DataMember(Name:="timestamp")> _
    Public Property Timestamp As String
    <DataMember(Name:="smtp-id")> _
    Public Property SmtpID As String
    <DataMember(Name:="response")> _
    Public Property Response As String
    <DataMember(Name:="sg_event_id")> _
    Public Property SgEventID As String
    <DataMember(Name:="event")> _
    Public Property [Event] As String
End Class

Open in new window

0
 
käµfm³d 👽Commented:
Create a class that mirrors the hierarchy you have in the JSON. Then install JSON.NET from NuGet. You can use the JsonConverter class to do the conversion.

e.g.

using System.Runtime.Serialization;

[DataContract]
public class LogItem
{
    [DataMember(Name = "email")]
    public string Email { get; set; }
    [DataMember(Name = "timestamp")]
    public int Timestamp { get; set; }
    [DataMember(Name = "smtp-id")]
    public string SmtpID { get; set; }
    [DataMember(Name = "response")]
    public string Response { get; set; }
    [DataMember(Name = "sg_event_id")]
    public string SgEventID { get; set; }
    [DataMember(Name = "event")]
    public string Event { get; set; }
}

Open in new window



List<LogItem> instance = (List<LogItem>)JsonConverter.Deserialize(jsonString);

Open in new window

0
 
Peter NordbergIT ManagerAuthor Commented:
Hi and thanks for answer,

Since there are several instances in the json string (the email, timestamp and so on is sent several times with differens status) do I need to iterate through it somehow?

Peter
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

 
Peter NordbergIT ManagerAuthor Commented:
If I would like to serialize so that I get the same format as the string I'm going to receive, how can i go about to do that? I get error when receiving the json string and would like to be able to debug it through sending a similar string to it locally.

Thanks for help!

Peter
0
 
käµfm³d 👽Commented:
Since there are several instances in the json string (the email, timestamp and so on is sent several times with differens status) do I need to iterate through it somehow?
My example deserailizes to a List, so yes you would iterate through it.

If I would like to serialize so that I get the same format as the string I'm going to receive, how can i go about to do that?
The JsonConvert class has a Serialize method as well.

e.g

string json = JsonConvert.SerializeObject(instance);

Open in new window


*Note:  In my previous comment, I called out the JsonConverter class. While this is a class offered by JSON.NET, it's not the one I intended to demonstrate. JsonConvert, which I demonstrate immediately above, is the correct class. So my previous example should have been:

List<LogItem> instance = (List<LogItem>)JsonConvert.Deserialize(jsonString);

Open in new window

0
 
Peter NordbergIT ManagerAuthor Commented:
Hi and thanks for answer,

I of course figured out that it was a list, thanks.

I don't have the option deserialize on the class of JsonConvert. You can see my options below. What should I choose?

JsonConvert
Thanks for help!

Peter
0
 
käµfm³d 👽Commented:
My apologies, I was trying to do it from memory. DeserializeObject is what you are looking for.
0
 
Peter NordbergIT ManagerAuthor Commented:
Hi again,

I tried this code:
 Dim json As String = "[{""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""}]"
        Dim instance As List(Of LogItem) = DirectCast(JsonConvert.DeserializeObject(json), List(Of LogItem))

Open in new window

But then I get this error:

could not convert Newtonsoft.Json.Linq.JArray to type System.Collections.Generic.List

How can I solve that?

Peter
0
 
Peter NordbergIT ManagerAuthor Commented:
Hi,

That worked perfectly and I can now receive the posts and insert it in my database.

Just one follow up question. Sometimes the json can be nested with an array of arguments like below:
{
  "unique_args": {
    "orderNumber": "12345",
    "eventID": "6789"
  }
}

Open in new window

How can that be represented in the class LogItem when I receive it?

Thanks for all your help!

Peter
0
 
käµfm³d 👽Commented:
Can you show how this array of arguments is laid out within the original JSON?
0
 
Peter NordbergIT ManagerAuthor Commented:
Hi,

It looks like this:
{ "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


Peter
0
 
käµfm³d 👽Commented:
Create a new class to represent that structure:

e.g.

<DataContract> _
Public Class Arguments
    <DataMember(Name:="tracking_id")> _
    Public Property TrackingID As String
    <DataMember(Name:="time_sent")> _
    Public Property TimeSent As String
    <DataMember(Name:="sender_username")> _
    Public Property SenderUsername As String
    <DataMember(Name:="recipient_username")> _
    Public Property RecipientUsername As String
End Class

Open in new window


...and then add a new property to the LogItem class of that type:

<DataContract> _
Public Class LogItem

...

    <DataMember(Name:="unique_args")> _
    Public Property UniqueArguments As Arguments
End Class

Open in new window


Nothing else should need to change.

Imports System.Runtime.Serialization
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Module Module1

    Sub Main()
        Dim jsonString As String = Module1.JSON()
        Dim instance As List(Of LogItem) = JsonConvert.DeserializeObject(Of List(Of LogItem))(jsonString)
    End Sub

    Function JSON() As String
        Return "[{" & _
"""email"": ""example@domain.none""," & _
"""timestamp"": 1386695691," & _
"""smtp-id"": ""<9b9f3ef952a66d57f5d995ae5969d389@swift.generated>""," & _
"""sg_event_id"": ""g_WdqUa0QRat0oHRS_HRlw""," & _
"""sg_message_id"": ""142dd810965.1c18.18bd41.filterdell-005.2437.52A74C0A8.0""," & _
"""event"": ""processed""" & _
"}, {" & _
"""email"": ""example@domain.none""," & _
"""smtp-id"": ""<9b9f3ef952a66d57f5d995ae5969d389@swift.generated>""," & _
"""timestamp"": 1386695693," & _
"""response"": ""250 2.0.0 OK 1386695693 sw1si11026220pbc.12 - gsmtp ""," & _
"""sg_event_id"": ""ODCueMfYSFWkXWixpIi62Q""," & _
"""event"": ""delivered""" & _
"}, {" & _
"""email"": ""example@domain.none""," & _
"""timestamp"": 1386695713," & _
"""ip"": ""66.249.84.39""," & _
"""useragent"": ""Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7 (via ggpht.com)""," & _
"""event"": ""open""" & _
"}, {" & _
"""email"": ""example@domain.none""," & _
"""smtp-id"": ""<142dd86a4be.197c.205564@localhost.localdomain>""," & _
"""timestamp"": 1386696059," & _
"""response"": ""250 2.0.0 OK 1386696059 ku6si10984836pbc.336 - gsmtp ""," & _
"""sg_event_id"": ""vwyR1ZoPQ06lnyOrbOIQWA""," & _
"""event"": ""delivered""" & _
"}, {" & _
"""email"": ""example@domain.none""," & _
"""timestamp"": 1386696071," & _
"""ip"": ""12.345.67.89""," & _
"""useragent"": ""Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7 (via ggpht.com)""," & _
"""event"": ""open""" & _
"}, {" & _
"""email"": ""example@domain.none""," & _
"""timestamp"": 1386696058," & _
"""smtp-id"": ""<142dd86a4be.197c.205564@localhost.localdomain>""," & _
"""sg_event_id"": ""IW2rrBkQSJys2Fw0zNuuEg""," & _
"""sg_message_id"": ""142dd86a4be.197c.205564.filterdell-006.16119.52A74D7A2.0""," & _
"""event"": ""processed""" & _
"" & _
"}, {" & _
"   ""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""" & _
"   }" & _
"}] "
    End Function
End Module



<DataContract> _
Public Class LogItem
    <DataMember(Name:="email")> _
    Public Property Email As String
    <DataMember(Name:="timestamp")> _
    Public Property Timestamp As String
    <DataMember(Name:="smtp-id")> _
    Public Property SmtpID As String
    <DataMember(Name:="response")> _
    Public Property Response As String
    <DataMember(Name:="sg_event_id")> _
    Public Property SgEventID As String
    <DataMember(Name:="event")> _
    Public Property [Event] As String
    <DataMember(Name:="category")> _
    Public Property Category As List(Of String)
    <DataMember(Name:="unique_args")> _
    Public Property UniqueArguments As Arguments
End Class

<DataContract> _
Public Class Arguments
    <DataMember(Name:="tracking_id")> _
    Public Property TrackingID As String
    <DataMember(Name:="time_sent")> _
    Public Property TimeSent As String
    <DataMember(Name:="sender_username")> _
    Public Property SenderUsername As String
    <DataMember(Name:="recipient_username")> _
    Public Property RecipientUsername As String
End Class

Open in new window

0
 
Peter NordbergIT ManagerAuthor Commented:
ok, super. I'll test that.

Peter
0
 
Peter NordbergIT ManagerAuthor Commented:
Very, very helpful! Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.