• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 375
  • Last Modified:

Create complex json string

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
JoeBo747
Asked:
JoeBo747
  • 5
  • 4
1 Solution
 
Christopher KileCommented:
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
 
JoeBo747Author Commented:
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
 
Christopher KileCommented:
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
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.

 
JoeBo747Author Commented:
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
 
Christopher KileCommented:
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
 
JoeBo747Author Commented:
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
 
Christopher KileCommented:
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
 
JoeBo747Author Commented:
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
 
Christopher KileCommented:
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: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

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

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now