Solved

Create complex json string

Posted on 2013-12-01
9
342 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
 
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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

708 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

16 Experts available now in Live!

Get 1:1 Help Now