Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Create complex json string

Posted on 2013-12-01
9
Medium Priority
?
373 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 1500 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
Introduction When many people think of the WebBrowser (http://msdn.microsoft.com/en-us/library/2te2y1x6%28v=VS.85%29.aspx) control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

636 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