Solved

Create complex json string

Posted on 2013-12-01
9
351 Views
Last Modified: 2014-01-31
Hi,

I am able to query a restful service by constructing the following string using jquery:

{ "driver" : "Driver", "_createdAt":{"$gte":{"$date":"2013-11-01T11:36:35.151Z"}}}

I need to do the same using .net preferable vb.net and I am unable to work out how to construct the nested date parameter.  I would like to build the date value as a parameter such as

Dim mydate As Date = DateAdd(DateInterval.Day, -30, DateTime.Now)
Dim sDate As String = Format(mydate, "yyyy-MM-ddTHH\:mm\:ss.fffZ")

and then pas the date into the string.  Does anyone know how to do this.  Any help would be much appreciated.
0
Comment
Question by:JoeBo747
  • 5
  • 4
9 Comments
 
LVL 23

Expert Comment

by:Christopher Kile
ID: 39691180
Yes. The method Date.ToString() can accept your format string:

Dim myDate as Date = DateAdd(DateInterval.Day, -30, DateTime.Now)
Dim sDate as String = myDate.ToString("yyyy-MM-dd") & "T" myDate.ToString("HH:mm:ss.fff") & "Z"

Open in new window


Note that this avoids any issues with T or Z potentially becoming format specifiers.
0
 
LVL 1

Author Comment

by:JoeBo747
ID: 39691256
Hi,  Thanks for your post,  I am happy with building the date element of the string but are you able to help with the construction of the entire json string?
0
 
LVL 23

Expert Comment

by:Christopher Kile
ID: 39691787
I'm missing part of what you need.  I see a JSON string which you have constructed, if by no other means, by hand.  What help do you need, other than the formatting?  

You mention jquery.  You know you can use jquery in ASP.NET apps, yes?  Have you tried this yet?
0
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
LVL 1

Author Comment

by:JoeBo747
ID: 39694132
Hi,

In vb.net I have attempted to construct the string using the json.net library as in:

                                       jsonWriter.WritePropertyName("driver")
                                       jsonWriter.WriteValue("DRIVER")

                                       jsonWriter.WritePropertyName("_createdAt" & "'" & ":{" & "'" & "$gte" & "'" & ":{" & "'" & "$date")
                                      jsonWriter.WriteValue(mydate)

This method obviously fails.  From what I have seen to use the json.net library correctly  I need to create a class with nested values and then populate the class object with the desired values and then cast the class as json using json.net.  But  cannot see how to construct the class to produce the correct json object as in the string produced in the original question.  Do you have any knowledge of this process?

Regards,
Joe
0
 
LVL 23

Expert Comment

by:Christopher Kile
ID: 39698640
Why aren't you trying to use the serialization functions of JSON.NET?  Your target string looks like a JSON object definition, and this link to the JSON.NET serialization documentation shows you in the first example how to generate a JSON string from a VB.NET object.  Here specifically is the page for serializing objects.  Study this for a bit, then let me know what your next question is.
0
 
LVL 1

Author Comment

by:JoeBo747
ID: 39704285
Hi,  I have been using the Json.net library to construct Jason strings including serializing class objects.  My question escrow to construct a class that would support the more complex example I posted in the question!
0
 
LVL 23

Expert Comment

by:Christopher Kile
ID: 39715174
Perhaps you could ask the question you actually want to ask now, please?  Because at this point I have no idea what you actually want.  Please be detailed and specific.
0
 
LVL 1

Author Comment

by:JoeBo747
ID: 39734397
Hi,  It goes back to my original question which I thought was straight forward;  how do I create this string in .net

{ "driver" : "Driver", "_createdAt":{"$gte":{"$date":"2013-11-01T11:36:35.151Z"}}}

I know that I have to use some sort of class or structure as the constructor of the string and then use the serialization functions of JSON.NET to convert the class or structure into the required string,  but I do not know how to go about constructing the class or structure!

The JSON holds two pieces of data the driver and the _createdAt $gte and $date are the operators.
0
 
LVL 23

Accepted Solution

by:
Christopher Kile earned 500 total points
ID: 39758481
It took me a while to get the time to play with this in code.  I apologize for taking so long but I've had a big backlog and, frankly, I'm not a JSON expert - I'd hope one would appear to take over this question.  However, I am one of the experts who accepts abandoned questions and gets an answer regardless of my current experience with the question.

To that end, I reconstructed some of your experiments.  

First, JSON.NET won't work because you can't create the fields with the necessary dollar sign ($) in the first name character.  

Second, while you can pass a date as a formatted string into a hidden variable, the Javascript Date constructor can't handle time zones or 24-hour dates naturally.

Third, I was able to create the object in Javascript by creating a Javascript Date, setting all its values using setUTC... functions (setUTCFullYEar(), etc.), then I printed out its date value using .toJSON():

    <script type="text/ecmascript" language="ecmascript">
    <!--
        var d = new Date();
        d.setUTCFullYear(2013, 11, 1);
        d.setUTCHours(11)
        d.setUTCMinutes(36,35,151);
        debugger;
        var test = JSON.parse('{ "driver" : "Driver", "_createdAt":{"$gte":{"$date":"' + d.toJSON() + '"}}}');
        alert("test.driver '" + test.driver + "'");
        alert("test._createdAt.$gte.$date '" + test._createdAt.$gte.$date + "'");
    -->
    </script>

Open in new window


The second alert displays the date formatted exactly as you wanted it.  Therefore, if you pass each component of your UTC date and time in separate hidden inputs, then substitute the integer values of those inputs into the code above, you'll get what you want.

However, there is the fourth option, which uses similar code to what I first gave you.  Here's the server code for my example:

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim myDate As Date = DateAdd(DateInterval.Day, -30, DateTime.UtcNow)
        Dim sDate As String = myDate.ToString("yyyy-MM-dd") & "T" & myDate.ToString("HH:mm:ss.fff") & "Z"
        createdAtParm.Value = sDate
        'createdAtParm.Value = d.ToString("yyyy-MM-dd HH:mm:ss.fff")
    End Sub
End Class

Open in new window


Here's the code for the client side:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="hidden" runat="server" id="createdAtParm" />    
    </div>
    <script type="text/ecmascript" language="ecmascript">
    <!--
       var test = JSON.parse('{ "driver" : "Driver", "_createdAt":{"$gte":{"$date":"' + d.toJSON() + '"}}}');
        alert("test.driver '" + test.driver + "'");
        alert("test._createdAt.$gte.$date '" + test._createdAt.$gte.$date + "'");
     -->
    </script>
    </form>
</body>
</html>

Open in new window


As you see, the date and time 30 days ago in Universal (Greenwich) Time (UTC) is now being displayed as the date parameter within the object created by your JSON string.  Is this OK?
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
More on Time zones in vb 2010 12 38
Variable Event ? 3 28
Write to file when application closes (by logoff) - VB.NET 1 32
get row value in vb.net 4 14
This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

810 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