如何动态设置JsonObject的属性?

时间:2014-02-24 21:30:12

标签: asp.net json vb.net system.json

我使用的方法是使用jquery和ajax将Json传递给我的标记。这可以在此页面上更详细地描述:http://blogs.telerik.com/aspnet-ajax/posts/12-04-27/the-present-and-future-of-using-json-in-webforms.aspx

在这段代码中,我尝试通过将名为“test”的字符串变量设置为业务对象的值来动态设置对象的值:

       Dim objOrder As Object = New JsonObject()
       For Each Order As BoVendorOrder In Orders
            Dim Vendor As New BoVendor(Order.VendorID)
            Dim test As String = Order.VendorOrderID
            objOrder.test = Vendor.VendorName + " - " + Order.VendorOrderPoNumber
       Next
为了简洁起见,我遗漏了一些代码。目标是使objOrder.test等于VendorOrderID(我们的SQL数据库中的数字),以便JSON看起来像这样:

       {
            "123456": "VendorName - PONumber",
            "678901": "VendorName - PONumber"
       }

你们中的任何一个人都知道如何做到这一点?

1 个答案:

答案 0 :(得分:1)

您真的需要订单ID作为对象的属性吗?返回序列化的Dictionary(Of String,String)可能更容易。您仍然可以通过订单ID查找,并且比Javascript对象的道具更容易循环。

以下是您使用字典方法需要做的一个示例:

Dim OrdersDict as New Dictionary(Of String, String)()  
For Each Order as BoVendorOrder In Orders  
    If Not OrdersDict.ContainsKey(Order.VendorOrderID) Then  
        OrdersDict.Add(Order.VendorOrderID, Vendor.VendorName + " - " + Order.VendorOrderPoNumber)
    End If
Next

' Serialize the dictionary object to JSON

' Using System.Web.Script.Serialization.JavascriptSerializer:
Dim Serializer As New JavaScriptSerializer
If MaxLength Then Serializer.MaxJsonLength = Int32.MaxValue
Dim x as String = Serializer.Serialize(OrdersDict) 'Return or response.write x as needed

'or

'Using JSON.net
Dim x as String = JsonConvert.SerializeObject(OrdersDict) 'Return or response.write x as needed