Solved

Deserialize JSON and put in object

Posted on 2013-12-17
14
479 Views
Last Modified: 2013-12-19
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
0
Comment
Question by:peternordberg
  • 8
  • 6
14 Comments
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 39724845
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
 

Author Comment

by:peternordberg
ID: 39725023
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
 

Author Comment

by:peternordberg
ID: 39725088
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
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 39725176
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
 

Author Comment

by:peternordberg
ID: 39725214
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
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 39725277
My apologies, I was trying to do it from memory. DeserializeObject is what you are looking for.
0
 

Author Comment

by:peternordberg
ID: 39726359
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 39727587
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
 

Author Comment

by:peternordberg
ID: 39728656
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
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 39728909
Can you show how this array of arguments is laid out within the original JSON?
0
 

Author Comment

by:peternordberg
ID: 39729360
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
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 39729497
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
 

Author Comment

by:peternordberg
ID: 39729507
ok, super. I'll test that.

Peter
0
 

Author Closing Comment

by:peternordberg
ID: 39729510
Very, very helpful! Thanks!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

705 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

19 Experts available now in Live!

Get 1:1 Help Now