Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Converting a json object into a datatable

Posted on 2011-10-10
7
Medium Priority
?
4,676 Views
Last Modified: 2012-05-12
How do you convert a json object

{ "mode": "collage", "objects": [ { "height": 207, "id": 46, "left": 370.333, "top": 76.4, "type": "image", "width": 276, "zIndex": 2 }, { "height": 40, "id": 109, "left": 364.383, "top": 283.4, "type": "word", "width": 95, "zIndex": 8 }, { "height": 40, "id": 91, "left": 527.783, "top": 187.4, "type": "word", "width": 170, "zIndex": 4 }, { "height": 75, "id": 107, "left": 199, "top": 167, "type": "word", "width": 264, "zIndex": 5 }, { "height": 55, "id": 30, "left": 321.667, "top": 250, "type": "image", "width": 73, "zIndex": 9 } ] }

into a datatable
0
Comment
Question by:JDEE8297
  • 4
  • 2
7 Comments
 
LVL 4

Expert Comment

by:guramrit
ID: 36946942
There're few ways to do this
1. Try JSON.NET (availaible from codeplex.com)
2. Parse it manually
3. Convert to dictionary then datatable. refer to following code, it converts json to dictionary
 
var serializer = new JavaScriptSerializer() ;
var obj = serializer.Deserialize<Dictionary<string, object>>("{ 'mode': 'collage', 'objects': [ { 'height': 207, 'id': 46, 'left': 370.333, 'top': 76.4, 'type': 'image', 'width': 276, 'zIndex': 2 }, { 'height': 40, 'id': 109, 'left': 364.383, 'top': 283.4, 'type': 'word', 'width': 95, 'zIndex': 8 }, { 'height': 40, 'id': 91, 'left': 527.783, 'top': 187.4, 'type': 'word', 'width': 170, 'zIndex': 4 }, { 'height': 75, 'id': 107, 'left': 199, 'top': 167, 'type': 'word', 'width': 264, 'zIndex': 5 }, { 'height': 55, 'id': 30, 'left': 321.667, 'top': 250, 'type': 'image', 'width': 73, 'zIndex': 9 } ] }");

Open in new window

0
 

Author Comment

by:JDEE8297
ID: 36949334
I tried using json.net and here was my attempt at it.

data_model.DicObjects there is nothing present in this object

and not sure why.
Imports _sysData = System.Data
Imports Newtonsoft.Json

''' <summary>
''' 
''' </summary>
''' <copyright>
''' My © 2011
''' </copyright>
''' <history>
''' My (My) - 10/11/2011
''' My-PC
''' </history>
Public Class Json_Data
    ''' <summary>
    ''' Gets or sets the type.
    ''' </summary>
    ''' <value>
    ''' The type.
    ''' </value>
    ''' <copyright>
    ''' My © 2011
    ''' </copyright>
    ''' <history>
    ''' My (My) - 10/11/2011
    ''' My-PC
    ''' </history>
    Public Property Type As String
        Get
            Return strType
        End Get
        Set(value As String)
            strType = value
        End Set
    End Property
    Private strType As String
    ''' <summary>
    ''' Gets or sets the index of the z.
    ''' </summary>
    ''' <value>
    ''' The index of the z.
    ''' </value>
    ''' <copyright>
    ''' My © 2011
    ''' </copyright>
    ''' <history>
    ''' My (My) - 10/11/2011
    ''' My-PC
    ''' </history>
    Public Property zIndex As Long
        Get
            Return lngZindex
        End Get
        Set(value As Long)
            lngZindex = value
        End Set
    End Property
    Private lngZindex As Long
    ''' <summary>
    ''' Gets or sets the width.
    ''' </summary>
    ''' <value>
    ''' The width.
    ''' </value>
    ''' <copyright>
    ''' My © 2011
    ''' </copyright>
    ''' <history>
    ''' My (My) - 10/11/2011
    ''' My-PC
    ''' </history>
    Public Property Width As Long
        Get
            Return lngWidth
        End Get
        Set(value As Long)
            lngWidth = value
        End Set
    End Property
    Private lngWidth As Long
    ''' <summary>
    ''' Gets or sets the top.
    ''' </summary>
    ''' <value>
    ''' The top.
    ''' </value>
    ''' <copyright>
    ''' My © 2011
    ''' </copyright>
    ''' <history>
    ''' My (My) - 10/11/2011
    ''' My-PC
    ''' </history>
    Public Property Top As Long
        Get
            Return lngTop
        End Get
        Set(value As Long)
            lngTop = value
        End Set
    End Property
    Private lngTop As Long
    ''' <summary>
    ''' Gets or sets the height.
    ''' </summary>
    ''' <value>
    ''' The height.
    ''' </value>
    ''' <copyright>
    ''' My © 2011
    ''' </copyright>
    ''' <history>
    ''' My (My) - 10/11/2011
    ''' My-PC
    ''' </history>
    Public Property height() As Long
        Get
            Return lngHeight
        End Get
        Set(value As Long)
            lngHeight = value
        End Set
    End Property
    Private lngHeight As Long
    ''' <summary>
    ''' Gets or sets the id.
    ''' </summary>
    ''' <value>
    ''' The id.
    ''' </value>
    ''' <copyright>
    ''' My © 2011
    ''' </copyright>
    ''' <history>
    ''' My (My) - 10/11/2011
    ''' My-PC
    ''' </history>
    Public Property id() As Long
        Get
            Return lngId
        End Get
        Set(value As Long)
            lngId = value
        End Set
    End Property
    Private lngId As Long
    ''' <summary>
    ''' Gets or sets the left.
    ''' </summary>
    ''' <value>
    ''' The left.
    ''' </value>
    ''' <copyright>
    ''' My © 2011
    ''' </copyright>
    ''' <history>
    ''' My (My) - 10/11/2011
    ''' My-PC
    ''' </history>
    Public Property left As Long
        Get
            Return lngLeft
        End Get
        Set(value As Long)
            lngLeft = value
        End Set
    End Property
    Private lngLeft As Long
End Class


''' <summary>
''' 
''' </summary>
''' <copyright>
''' My © 2011
''' </copyright>
''' <history>
''' My (My) - 10/11/2011
''' My-PC
''' </history>
Public Class Json_Model
    Public Property DicObjects() As Dictionary(Of Integer, Json_Data)
        Get
            Return dicObject
        End Get
        Set(value As Dictionary(Of Integer, Json_Data))
            dicObject = value
        End Set
    End Property
    Private dicObject As Dictionary(Of Integer, Json_Data)
End Class
''' <summary>
''' 
''' </summary>
''' <copyright>
''' My © 2011
''' </copyright>
''' <history>
''' My (My) - 10/11/2011
''' My-PC
''' </history>
Partial Class participant_view
    Inherits cPageBase


#Region "Module Level Variables"
    'User defined object
    Private _DataAccess As New cDataAccess
    Private _ErrorHandler As New cErrorHandler
    Private _ExpressionExercise As New cExpressionExercise

    'Strings
    Private _strErrMsg As String = String.Empty
    Private _strExerciseName As String = String.Empty
    'Boolean
    Private _blnErrorOccurred As Boolean = False
    'Long
    Private _lngExerciseId As Long = 0
    Private _lngFacId As Long = 0
    'Constants
    Const _cstrMODULE_NAME As String = "content_dialog"
#End Region


#Region "Page Events"
    ''' <summary>
    ''' Handles the Load event of the Page control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
    ''' <copyright>
    ''' My, Inc. © 2008
    ''' </copyright>
    ''' <history>
    ''' My (My) - 6/4/2008
    ''' </history>
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Local variables

        'Give it a whirl
        Try
            'Pull back values
            Long.TryParse(GetQueryStringFormValue("uid"), _lngFacId)
            Long.TryParse(GetQueryStringFormValue("itmid"), _lngExerciseId)
            _strExerciseName = GetQueryStringFormValue("fn")
            'Check to see if you continue or not
            If _lngExerciseId > 0 And _lngFacId > 0 Then
                'Connect to the database
                If SetupDataBaseConnection(_DataAccess) Then
                    With _ExpressionExercise
                        'Set the object properties
                        .SetDatabaseConnection = _DataAccess
                        .SetErrorHandler = _ErrorHandler
                        'Pull back the details for the selected view
                        If Not .GetExerciseView(_lngFacId, _lngExerciseId, _strExerciseName) Then
                            Response.Write(.GetErrorMsg)
                        Else
                            Dim strJson As String
                            strJson = .ExerciseView.Rows(0)("item_data").ToString.Trim()
                            Response.Write(strJson & "<br>")
                            Dim data_model As Json_Model = JsonConvert.DeserializeObject(Of Json_Model)(strJson)

                            For lngIdx As Long = 0 To data_model.DicObjects.Count - 1

                                Response.Write(data_model.DicObjects.Item(lngIdx).id)
                            Next
                        End If
                    End With
                End If
            End If
        Catch ex As Exception
            'Store the error message in ELMAH database
            _ErrorHandler.LogError(Context, ex)
            Response.Write(ex.Message)

        End Try

    End Sub

    ''' <summary>
    ''' Handles the PreRender event of the Page control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
    ''' <copyright>
    ''' My, Inc. © 2008
    ''' </copyright>
    ''' <history>
    ''' My (My) - 6/11/2008
    ''' </history>
    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        'Local variables
        'Give it a whirl
        Try

        Catch ex As Exception
            'Store the error message in ELMAH database
            _ErrorHandler.LogError(Context, ex)
        Finally
            If Not IsNothing(_DataAccess) Then
                'Close the database connection
                With _DataAccess
                    If .IsDbOpen Then
                        CloseDatabaseConnection(_DataAccess)
                    End If
                End With
            End If
        End Try
    End Sub

#End Region
#Region "ASP.NET Control Events"

#End Region
#Region "Third Party Control Events"

#End Region
#Region "Public Properties - Read/Write"
    ''' <summary>
    ''' Gets or sets the error MSG.
    ''' </summary>
    ''' <value>The error MSG.</value>
    ''' <copyright>
    ''' My, Inc. © 2008
    ''' </copyright>
    ''' <history>
    ''' My (My) - 3/31/2008
    ''' Created the property ErrorMsg
    ''' </history>
    Public Property ErrorMsg() As String
        Get
            Return _strErrMsg
        End Get
        Set(ByVal value As String)
            _strErrMsg = value
        End Set
    End Property
    ''' <summary>
    ''' Gets or sets a value indicating whether [error occurred].
    ''' </summary>
    ''' <value><c>true</c> if [error occurred]; otherwise, <c>false</c>.</value>
    ''' <copyright>
    ''' My, Inc. © 2008
    ''' </copyright>
    ''' <history>
    ''' My (My) - 3/31/2008
    ''' Created the property ErrorOccurred
    ''' </history>
    Public Property ErrorOccurred() As Boolean
        Get
            Return _blnErrorOccurred
        End Get
        Set(ByVal value As Boolean)
            _blnErrorOccurred = value
        End Set
    End Property
#End Region
#Region "Public Properties - Read"
#End Region
#Region "Public Properties - Write"



#End Region
#Region "Private Procedures and Methods"

#End Region
#Region "Public Procedures and Methods"
#End Region
#Region "Class Events"


    ''' <summary>
    ''' Allows an <see cref="T:System.Object"></see> to attempt to free resources and perform other cleanup operations before the <see cref="T:System.Object"></see> is reclaimed by garbage collection.
    ''' </summary>
    ''' <copyright>
    ''' My, Inc. © 2008
    ''' </copyright>
    ''' <history>
    ''' My (My) - 3/31/2008
    ''' Created the function for the first time.
    ''' </history>
    Protected Overrides Sub Finalize()
        _DataAccess = Nothing
        _ErrorHandler = Nothing
        MyBase.Finalize()
    End Sub
#End Region


End Class

Open in new window

0
 
LVL 83

Assisted Solution

by:CodeCruiser
CodeCruiser earned 100 total points
ID: 36949928
See if this tool is of any help

http://jsonclassgenerator.codeplex.com/
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:JDEE8297
ID: 36950182
@guramrit:

how would you access the individual records in this set up using
var serializer = new JavaScriptSerializer() ;
var obj = serializer.Deserialize<Dictionary<string, object>>("{ 'mode': 'collage', 'objects': [ { 'height': 207, 'id': 46, 'left': 370.333, 'top': 76.4, 'type': 'image', 'width': 276, 'zIndex': 2 }, { 'height': 40, 'id': 109, 'left': 364.383, 'top': 283.4, 'type': 'word', 'width': 95, 'zIndex': 8 }, { 'height': 40, 'id': 91, 'left': 527.783, 'top': 187.4, 'type': 'word', 'width': 170, 'zIndex': 4 }, { 'height': 75, 'id': 107, 'left': 199, 'top': 167, 'type': 'word', 'width': 264, 'zIndex': 5 }, { 'height': 55, 'id': 30, 'left': 321.667, 'top': 250, 'type': 'image', 'width': 73, 'zIndex': 9 } ] }");

@Codecruiser
Thanks for the little tool, I may use, but I want to see how I can parse these items out in individual records
0
 
LVL 4

Accepted Solution

by:
guramrit earned 400 total points
ID: 36950518
You've two methods to get values from json string. Use whichever is easy to you.
note: You need to add reference System.Web.Extensions

1.
 
var serializer = new JavaScriptSerializer();
Dictionary<string, object> dic1 = serializer.Deserialize<Dictionary<string, object>>("{ 'mode': 'collage', 'objects': [ { 'height': 207, 'id': 46, 'left': 370.333, 'top': 76.4, 'type': 'image', 'width': 276, 'zIndex': 2 }, { 'height': 40, 'id': 109, 'left': 364.383, 'top': 283.4, 'type': 'word', 'width': 95, 'zIndex': 8 }, { 'height': 40, 'id': 91, 'left': 527.783, 'top': 187.4, 'type': 'word', 'width': 170, 'zIndex': 4 }, { 'height': 75, 'id': 107, 'left': 199, 'top': 167, 'type': 'word', 'width': 264, 'zIndex': 5 }, { 'height': 55, 'id': 30, 'left': 321.667, 'top': 250, 'type': 'image', 'width': 73, 'zIndex': 9 } ] }");
string mode = (string)dic1["mode"];
Dictionary<string, object>[] objects = (Dictionary<string, object>[])((ArrayList)dic1["objects"]).ToArray(typeof(Dictionary<string, object>));
int height = (int)objects[0]["height"];

Open in new window

2.
 
public class JsonModel
{
    public string mode;
    public JsonObject1[] objects;
}

public class JsonObject1
{
    public int height;
    public int id;
    public double left;
    public double top;
    public string type;
    public double width;
    public int zIndex;
}

static void Main(string[] args)
{
    var serializer = new JavaScriptSerializer();
    JsonModel model = serializer.Deserialize<JsonModel>("{ 'mode': 'collage', 'objects': [ { 'height': 207, 'id': 46, 'left': 370.333, 'top': 76.4, 'type': 'image', 'width': 276, 'zIndex': 2 }, { 'height': 40, 'id': 109, 'left': 364.383, 'top': 283.4, 'type': 'word', 'width': 95, 'zIndex': 8 }, { 'height': 40, 'id': 91, 'left': 527.783, 'top': 187.4, 'type': 'word', 'width': 170, 'zIndex': 4 }, { 'height': 75, 'id': 107, 'left': 199, 'top': 167, 'type': 'word', 'width': 264, 'zIndex': 5 }, { 'height': 55, 'id': 30, 'left': 321.667, 'top': 250, 'type': 'image', 'width': 73, 'zIndex': 9 } ] }");
    //Do something with model
}

Open in new window

0
 

Author Comment

by:JDEE8297
ID: 36950840
Some of it is my own personal code, but I managed to get json.net to work.

 'Set up datatable for views
                            Dim dtView As New _sysData.DataTable
                            Dim arrFields As New ArrayList
                            With arrFields
                                .Add("id|I")
                                .Add("height|D")
                                .Add("left|D")
                                .Add("top|D")
                                .Add("width|D")
                                .Add("imgfile|S")
                            End With
                            _DataAccess.MakeDataTable(dtView, arrFields)

                            Dim JsonObj As New JObject
                            JsonObj = JObject.Parse(strJson)
                            For Each jo As KeyValuePair(Of String, JToken) In JsonObj
                                If jo.Key.ToLower.ToString = "objects" Then
                                    For Each itm As Object In jo.Value
                                        Dim drRow As _sysData.DataRow
                                        drRow = dtView.NewRow
                                        drRow("id") = itm.SelectToken("id").ToString
                                        drRow("height") = itm.selecttoken("height").ToString
                                        drRow("left") = itm.selecttoken("left").ToString
                                        drRow("top") = itm.selecttoken("top").ToString
                                        drRow("width") = itm.selecttoken("width").ToString
                                        drRow("imgfile") = ""
                                        dtView.Rows.Add(drRow)
                                        'Response.Write(jo.Value.Item(itm).SelectToken("id")))
                                    Next
                                End If
                            Next
0
 

Author Closing Comment

by:JDEE8297
ID: 36950849
thank you for your help.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?
Suggested Courses

580 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