Newtonsoft JSON解析为对象

时间:2018-09-20 12:44:35

标签: json vb.net visual-studio class json.net

我的VB有点生锈,但是我需要解析一个JSON字符串。我已经在没有问题的C#中做到了。这是一个旧项目,我正在使用VS2008。 这是我的课程:

Public Class ResponseMeta
    Private _type As String
    <JsonProperty("type")> _
    Public Property type() As String
        Get
            Return _type.ToString()
        End Get
        Set(ByVal value As String)
            _type = value
        End Set
    End Property

    Private _message As String
    <JsonProperty("message")> _
    Public Property message() As String
        Get
            Return _message
        End Get
        Set(ByVal value As String)
            _message = value
        End Set
    End Property

    Private _message_v1 As String
    <JsonProperty("message-v1")> _
    Public Property message_v1() As String
        Get
            Return _message_v1
        End Get
        Set(ByVal value As String)
            _message_v1 = value
        End Set
    End Property

    Private _message_v2 As String
    <JsonProperty("message-v2")> _
    Public Property message_v2() As String
        Get
            Return _message_v2
        End Get
        Set(ByVal value As String)
            _message_v2 = value
        End Set
    End Property

    Private _message_v3 As String
    <JsonProperty("message-v3")> _
    Public Property message_v3() As String
        Get
            Return _message_v3
        End Get
        Set(ByVal value As String)
            _message_v3 = value
        End Set
    End Property

    Private _message_v4 As String
    <JsonProperty("message-v4")> _
    Public Property message_v4() As String
        Get
            Return _message_v4
        End Get
        Set(ByVal value As String)
            _message_v4 = value
        End Set
    End Property 
End Class

要反序列化的代码是:

Dim test As String
test = "{""response-meta"":{""type"":""S"",""message"":"""",""Total No Of Records"":"""",""message-v1"":""1"",""message-v2"":"""",""message-v3"":"""",""message-v4"":""""}}"
Dim testcl As ResponseMeta
testcl = JsonConvert.DeserializeObject(Of ResponseMeta)(test)

该对象的所有属性均设置为Nothing,如果添加监视,它会显示:

  

type = {“对象引用未设置为对象的实例。”}

我现在在此上花费了无数的时间,而Google并未发现此处可能出问题的提示或线索。

任何建议都非常欢迎。

1 个答案:

答案 0 :(得分:0)

JSON与您要解析的JSON不匹配。

您缺少根对象。

List<JsonNode> jsonNodes = arrayNodeToListNode((ArrayNode) t.get("coverageList"));
List<JsonNode> collect = jsonNodes.stream()
    .filter(Objects::nonNull)
    .map(node -> node.get("/coverage/coverageTypeLevel"))
    ...

因此,基于JSON,您需要先反序列化为根对象,然后获取元数据

Public Class RootObject
    Private _root As ResponseMeta
    <JsonProperty("response-meta")> _
    Public Property ResponseMeta() As ResponseMeta
        Get
            Return _root 
        End Get
        Set(ByVal value As ResponseMeta)
            _root = value
        End Set
    End Property
End Class