0

我希望有人能够为我指出关于 Json 格式的正确方向。

我以前从未真正使用过 Json 和序列化,所以它有点新。

我需要以以下格式从 .Net 返回一个 Json。

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

我快到了,但我正在为字符串的格式而苦苦挣扎,因为默认情况下,字符串是被引用的。这就是我所拥有的:

        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)

这将返回 Json,如下所示,除了环绕时间字符串的双引号之外,它是完美的。

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

如果有人能指出我如何更改代码以便正确格式化字符串的正确方向,我将不胜感激。

谢谢。

4

2 回答 2

0

您想要的不是有效的 JSON(引号之外的“日期” - 请参阅http://www.json.org上的规范),因此您不能真正使用 JSON 序列化程序来做到这一点。您可能需要做的是进行一些简单的字符串操作:

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) + "]"
于 2012-05-17T15:05:22.010 回答
0

像这样将 Linq 与 StringBuilder 一起使用:

    Dim query = db.Employees.Select(Function(q) New With {q.EmployeeID, q.LastName}).ToList()
    Dim json As New JavaScriptSerializer
    Dim sb As New StringBuilder
    For Each rows In query
    sb.Append(rows.LastName)
    Next
    Dim strjson As String = json.Serialize(Convert.ToString(sb))
    Response.Write(strjson)
于 2012-05-17T13:28:11.740 回答