首页 > 解决方案 > 使用 vb.net 无法正确地从数组转换为 json 数组?

问题描述

我正在尝试将数组转换为 json 数组。我所拥有的是:

我创建了一个类,我在其中声明要使用的字段。

Public Class Response
    Public container As Array
    Public signature As Tuple(Of Object, String, Integer, String, Object, String)

    Sub New()
        Me.container = Nothing
        Me.signature = Nothing
    End Sub

    Sub New(ByVal container As Array,
            ByVal signature As Tuple(Of Object, String, Integer, String, Object, String))
        Me.container = container
        Me.signature = signature
    End Sub
End Class

以及我想将它们转换为 JSON 以便使用的函数:

Public Function GetResponse()
    Dim response As New Response

    response.container = {"none", False}
    response.signature = New Tuple(Of Object, String, Integer, String, Object, String)({10, 10}, 
        "IT", 1, "Testing", {100, 100}, "Test Signature")
    Dim JSONString As String = JsonConvert.SerializeObject(response)

    Return JSONString
End Function

我希望它看起来像:

        { "container": {
            "type": "none",
            "single": false
        },
      "signature": {
            "coordinates": {
                "x": 10,
                "y": 10
            },
            "location": "IT",
            "page": 1,
            "reason": "Testing",
            "size": {
                "height": 100,
                "width": 100
            },
            "value": "Test Signature"
            }
    }

但它看起来是这样的:

{
  "container": [
    "none", false
  ],
  "signature": {
    "Item1": [10, 10],
    "Item2": "IT",
    "Item3": 1,
    "Item4": "Testing",
    "Item5": [100, 100],
    "Item6": "Test Signature"
  }
}

我是新手,我会给予任何帮助:)提前致谢!

标签: jsonvb.netjson.net

解决方案


这就是使用元组的问题;这些属性没有您可以选择的名称。如果您不想为这些数据创建一个完整的类(并使用谷歌搜索“将 JSON 粘贴为类”;没有太多理由不拥有它们),请使用匿名类型:

Dim response = New With { _
  .container = New With { .type = "none", .single = false }, _
  .signature = New With { _
    .coordinates = New With { .x = 10, .y = 10 }, _
    .location = "IT", _

    .someOtherName = someOtherValue, _

    ... etc ...

}

推荐阅读