【问题标题】:How to create JSON array using vb.net如何使用 vb.net 创建 JSON 数组
【发布时间】:2012-03-05 08:41:41
【问题描述】:

如何使用vb.net 数组创建这个JSON 数组

var data = {items: [
{value: "21", name: "Mick Jagger"},
{value: "43", name: "Johnny Storm"},
{value: "46", name: "Richard Hatch"},
{value: "54", name: "Kelly Slater"},
{value: "55", name: "Rudy Hamilton"},
{value: "79", name: "Michael Jordan"}
]};

【问题讨论】:

标签: vb.net arrays json


【解决方案1】:

当您使用 .NET 2.0 时,您必须使用 James 的 JSON 库,可在 Codeplex 下载(.NET 2.0 版)。

使用 Json.NET 的示例

在您的类中添加对 Newtonsoft.Json 的引用,以及 Import Newtonsoft.Json

例子:

Import Newtonsoft.Json

Dim product As New Product()
product.Name = "Captopril"
product.Expiry = New DateTime(2008, 12, 28)
product.Price = 3.99D
product.Sizes = New String() {"Small", "Medium", "Large"}


'Call SeralizeObject to convert the object to JSON string'
Dim output As String = JavaScriptConvert.SerializeObject(product)

输出变量将保存值:

{
  "Name": "Captopril",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}

【讨论】:

  • 这不起作用。它说 Product() 和 JavaScriptConvert 都没有定义。
  • 是的,我使用 NuGet 控制台安装了必要的依赖项
【解决方案2】:
Public Class Student
    Public Property value As String
    Public Property name As Integer
End Class

在 Page_Load 上:

'creating sample student ojects
    Dim obj1 As New Student() With {.value = "Mick Jagger", .name = 21}
    Dim obj2 As New Student() With {.value = "Johnny Storm", .name = 43}
    Dim obj3 As New Student() With {.value = "Richard Hatch", .name = 46}
    Dim obj4 As New Student() With {.value = "Kelly Slater", .name = 54}
    'adding student objects to list
    Dim objStudentList As New List(Of Student)() From { obj1,obj2, obj3, obj4}

    Dim objJSSerializer As New System.Web.Script.Serialization.JavaScriptSerializer()

    'Serialization .NET Object to JSON
    strJSON = objJSSerializer.Serialize(objStudentList)

    Dim csname2 As String = "ButtonClickScript"
    Dim cstype As Type = Me.GetType()
    Dim cstext2 As New StringBuilder()
    Dim cs As ClientScriptManager = Page.ClientScript
    cstext2.Append("<script type=""text/javascript""> var data = {items: " + strJSON)
    cstext2.Append(" }; </")
    cstext2.Append("script>")
    cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), False)

【讨论】:

    【解决方案3】:

    查看名为 JSON.net 的 Visual Studio 库扩展或转到他们的 codeplex 页面 (JSON on codeplex)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 2018-11-15
      • 2011-02-02
      • 1970-01-01
      • 2015-06-07
      • 1970-01-01
      相关资源
      最近更新 更多