VB.Net's JSON Serialization Structure

Could someone please provide guidance on the proper format for a Json? I am new to working with Json and Serialization.

I need to generate a Json from .Net in this specific format:

[[Date.UTC(2011,12,14,8), 8], [Date.UTC(2011,12,14,9), 1]]

I am close to achieving this but struggling with the formatting of my string, as it is automatically enclosed in quotes. Here is my current code snippet:

        Dim oSerializerDt As New JavaScriptSerializer()

        Dim dt As New DataTable
        dt.Columns.Add("Date", GetType(String))
        dt.Columns.Add("Count", GetType(Integer))

        objresults.GetResults(id, period)

        Dim listResults As New List(Of Object())

        Dim newDate As String
        For Each result As Application.NewResults In objresults
            newDate = "Date.UTC(" + result.EventDate.Year.ToString + "," + result.EventDate.Month.ToString + "," + result.EventDate.Day.ToString + "," + result.EventDate.Hour.ToString + ")"
            listResults.Add({newDate, result.Count})
        Next

        Return oSerializerDt.Serialize(listResults)

The generated Json looks like this, with double quotes around the time string:

[["Date.UTC(2011,12,14,8)",8],["Date.UTC(2011,12,14,9)",11]]

I would greatly appreciate any advice on how to modify my code to ensure the strings are correctly formatted. Thank you!

Best regards.

Answer №1

Employing Linq in conjunction with StringBuilder can streamline your code like so:

    Dim data = db.Users.Select(Function(u) New With {u.UserID, u.Username}).ToList()
    Dim serializer As New JavaScriptSerializer
    Dim builder As New StringBuilder
    For Each entry In data
        builder.Append(entry.Username)
    Next
    Dim jsonStr As String = serializer.Serialize(Convert.ToString(builder))
    Response.Write(jsonStr)

Answer №2

Your request doesn't adhere to the JSON specification (having 'Date' outside of quotes). As a result, using a JSON serializer won't work in this case. To achieve your goal, you should consider simple string manipulation instead:

Dim dt As New DataTable 
dt.Columns.Add("Date", GetType(String)) 
dt.Columns.Add("Count", GetType(Integer)) 

objresults.GetResults(id, period) 

Dim listResults As New List(Of String)

Dim newDate As String 
For Each result As Application.NewResults In objresults 
    newDate = "Date.UTC(" + result.EventDate.Year.ToString + "," + result.EventDate.Month.ToString + "," + result.EventDate.Day.ToString + "," + result.EventDate.Hour.ToString + ")" 
    listResults.Add(String.Format("[{0}, {1}]", newDate, result.Count)
Next

Return "[" + String.Join(", ", listResults) + "]"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Working with Javascript objects and arrays

Need assistance with manipulating/updating a JavaScript array. Hoping for some help. The initial array looks like this: array('saved_designs'=array()); In Javascript JSON format: {"saved_design":{}} I plan on adding a label and its associa ...

There are times when window.onload doesn't do the trick, but using alert() can make

I recently posted a question related to this, so I apologize for reaching out again. I am struggling to grasp this concept as I am still in the process of learning JavaScript/HTML. Currently, I am loading an SVG into my HTML using SVGInject and implementi ...

Encountering a Next.js error while trying to link to a dynamic page

My current folder structure is as follows: - blog (directory) -- index.js (list of all blog articles) -- [slug].js (single article) Whenever I am inside index.js, the code looks like this: const Blog = props => { const { pageProps: { articles } } = ...

Entity characteristics duplicated in serialization

When working with Spring 3.3, I encountered an issue with an entity class mapped to a database table. All properties in the entity are annotated with @JsonProperty, such as @JsonProperty("ID"). In the controller, a service is called to retrieve this entit ...

While I have the ability to include an overlay, I unfortunately lack the capability to delete it using jQuery

This feature will create an overlay on the entire browser screen using the defined properties. $('a.cell').click(function() { $('<div id = "overlay" />').appendTo('body').fadeIn("slow"); }); #overlay { backgroun ...

Struggling with updating the header in React Navigation?

Having trouble updating the screen header in my react native application when navigating to the Dashboard Screen after login. I've tried different methods but can't seem to figure out what's wrong. After logging in, I navigate to the Dashbo ...

Directive in Angular for customer management with filtering and sorting functionality

I am struggling to organize the JSON object by userType using ng-repeat. While I have successfully retrieved and displayed the data, my ISSUE is that I need to sort and display two different tables for the following list: One for MARRIED individuals and an ...

Altering Image Order Across Various Slides

I have customized a parallax website template that is divided into various sections and slides. I want to incorporate a fixed image sequence on each slide that animates based on the scroll position. With 91 images in the animation sequence, it moves quickl ...

In what situations is it beneficial to utilize inherited scope, and when is it best to avoid it

Is it better to use inherited scope (i.e scope:true) when creating a directive, or is it more appropriate not to use it (i.e scope:false)? I grasp the distinction between scope types and their respective functionalities. However, I am uncertain about whic ...

When subjecting an ASP.NET application to load testing with 100 users using JMeter, an error related to jQuery functionality is

As part of load testing for my asp.net application using jmeter, I am simulating only 100 users. The issue arises when jQuery is present on the page at "Scripts/jquery.min.js" and an error occurs in 20% of cases as shown below: Sample Result :- Thread N ...

Tips for conducting key down event testing on a material ui MenuList element utilizing react-testing-library

Looking to test the key down event on my MenuList component. Component: import MenuItem from '@material-ui/core/MenuItem'; import MenuList from '@material-ui/core/MenuList'; import * as React from 'react'; export default fu ...

Dynamic and static slugs in Next.js routing: how to navigate efficiently

I am facing a scenario where the URL contains a dynamic slug at its base to fetch data. However, I now require a static slug after the dynamic one to indicate a different page while still being able to access the base dynamic slug for information. For Ins ...

create undirected lists using an array

I am trying to convert an array of sentences into unordered HTML lists, with each list item containing a word from the sentence. For example: [I play piano the can'] t <ul> <li id = number</li> <li>I</li> <li>play< ...

Launch a Word document directly from an ASP.NET application

When I press Ctrl+F5 in Visual Studio, the following code snippet allows me to open a local docx file with no issues. A simple click of the button opens Word2007 on my machine and displays the docx. However, after deploying the application to the productio ...

Tips for managing double values in JSON in Scala

Given { "currency" : { "details" : { "data" : { "code" : "INR", "name" : "Indian Rupee", "symbol" : "₹" } } }, "amt ...

Having trouble with jQuery not recognizing onclick events on dynamic ids?

I've created a dropdown that generates dynamic IDs when 'add' is clicked, such as option-1, option-2. However, I'm facing issues with implementing an onclick action on these dynamically generated IDs. I require the onclick action to be ...

"Customizing the MsAdalAngular6Module setup on the fly - a step-by-step

In order to manage authentication in an Angular single page app, I am utilizing the microsoft adal wrapper available at https://github.com/manishrasrani/ms-adal-angular6. Following the documentation, I configure all necessary options during compile time u ...

Tips for Messaging from a Website to the Telegram App

On my website, I have a share button and I'm looking to send a specific message to contacts on the Telegram app when accessed from a mobile device. The issue is that I haven't been able to find the complete code, as it only opens the app on the ...

While working with AJAX, the variable value remains static and is not refreshed

My jQuery code successfully calls a REST Service and handles the response in the AJAX Success event. However, I'm facing an issue where the variable "SelectedVal" (document.getElementById('Text1').value) is not getting updated with each cli ...

What is the most effective method for live-updating a field every 5 seconds in Laravel?

I want to monitor the database to see if a new row is created for each user and display a popup message to notify them. I'm debating between using pusher/socket or making an Ajax call every 5 seconds to achieve this live update without page refresh. I ...