用Newtonsoft解析Json字符串

时间:2016-11-22 01:24:50

标签: .net json vb.net

我有一个JSON对象,我存储在由其创建的数据库中         var data = JSON.stringify($('#frm')。serializeArray());我想调用它并使用Newtonsoft.json将其解析为它的部分。我完全错综复杂的VB.Net代码是(不要选择我,我知道它是一个黑客)

     Dim reader As JsonTextReader = New JsonTextReader(New StringReader(TextBox1.Text))
    Dim firstname As String = ""
    Dim middleInitial As String = ""
    Dim lastName As String = ""


    While (reader.Read())

        Select Case reader.Value
            Case "disFirst"
                reader.Read()
                reader.Read()
                firstname = reader.Value
            Case "disMiddle"
                reader.Read()
                reader.Read()
                middleInitial = reader.Value
            Case "disLast"
                reader.Read()
                reader.Read()
                lastName = reader.Value
        End Select
    End While

    MessageBox.Show(firstname + " " + middleinitial + " " + lastName)

但它确实有效。我100%知道有很多更好的方法,所以如果有人可以指出我在正确的VB.Net方向,这将是伟大的。我的Json字符串是

    [{"name":"disFirst","value":"Robert"},{"name":"disMiddle","value":"S"},{"name":"disLast","value":"Smith"},{"name":"disSuffix","value":""},{"name":"disEmail","value":"Smith@xxxxxxx.edu, 12345@zzzzz.edu"},{"name":"disAffiliations","value":"Arizona\r\nXXXX"},{"name":"disPMIDlist","value":""},{"name":"disThreshholdFactor","value":""}]

1 个答案:

答案 0 :(得分:1)

那个json更有点不稳定。它似乎是在描述一个实体,而不是一个带有firstname,lastname等的对象,它只是一组名称对。只要那里只有一个实体,我想它可以起作用。

这会将json反序列化为一组名称对:

Public Class NameValuePair
    Public Property name As String
    Public Property value As String
End Class

然后反序列化:

Dim jstr = from whereever
Dim myNVPs = JsonConvert.DeserializeObject(Of NameValuePair())(jstr)

name将包含disLastvalue这些可怕的关键数据。作为一个数组,你可以通过它循环来获取数据。