user1314159 user1314159 - 7 months ago 42
JSON Question

parse a Json string with Newtonsoft

I have a JSON object that I store in a database that is created by
var data = JSON.stringify($('#frm').serializeArray()); I want to call it and use Newtonsoft.json to parse it out into it's parts. My totally convoluted VB.Net code is (Dont pick on me I know it is a hack)

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)


but it works. I 100% know that there are MUCH better ways so if someone can point me in the right VB.Net direction that would be great. My Json string is

[{"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":""}]

Answer

That json is more that a little wonky. It appears to be describing an entity, but rather than an object with firstname, lastname etc it is just a set of name pairs. As long as there is just one entity there, I guess it could work.

This will deserialize the json to an array of name pairs:

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

Then to deserialize:

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

The name will contain those awful keys like disLast and value will be the related data. As an array you can loop thru it to get the data.