Solved

Create complex json string

Posted on 2013-12-01
9
364 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

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 …
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

691 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