在mvc 4 vb.net中以json的形式返回对象列表

时间:2015-02-11 08:08:14

标签: json asp.net-mvc vb.net asp.net-mvc-4

我需要返回以下json:

 [
{
    "tag": "test",
    "values": [
        {
            "en": "english text",
            "ar": "arabic text"
        },
        {
            "en": "english text",
            "ar": "arabic text"
        }
    ]
},
{
    "tag": "test2",
    "values": [
        {
            "en": "english text",
            "ar": "arabic text"
        },
        {
            "en": "english text",
            "ar": "arabic text"
        }
    ]
}
]

我需要在mvc4.net中返回上面的json,所以我尝试创建以下类:

 Public Class AppLabels
    Public Property labels As New labelsTag()
End Class

Public Class labelsTag
    Public Property tag As String = ""
    Public Property values As DataTable
End Class

但是我无法设置labelsTag的列表,换句话说我无法写出:

   labels.labels(0).tag_name = "test"
   labels.labels(0).values = datatable1

因为labels.labels未被视为数组......

任何帮助PLZ ..

1 个答案:

答案 0 :(得分:2)

首先,您需要为此节点创建一个类:

 {
   "en": "english text",
   "ar": "arabic text"
 }

班级将是:

Public Class value

    Public en As String

    Public ar As String
End Class

然后这个json部分

 {
        "tag": "test",
        "values": [
            {
                "en": "english text",
                "ar": "arabic text"
            },
            {
                "en": "english text",
                "ar": "arabic text"
            }
        ]
    }

将代表:

Public Class Smalljson

    Public tag As String

    Public values As List(Of value)
End Class

最后一堂课最后一堂课将是:

    Public Class finaljson

       Public json As List(Of Smalljson)
    End Class

示例如何使用:

 Dim json As finaljson = New finaljson
 Dim j As Integer = 0
 Do While (j < 2)
    Dim sj As Smalljson = New Smalljson
    sj.tag = ("test" + j)
    Dim i As Integer = 0
    Do While (i < 2)
        Dim v As value = New value
        v.en = ("english text" + i)
        v.ar = ("arabic text" + i)
        sj.values.Add(v)
        i = (i + 1)
    Loop
    json.Add(sj)
    j = (j + 1)
Loop

注意:我没有测试代码,但我想它应该可以正常工作

干杯!