I am creating vb.net application. I am getting Json data from google finance. I am facing a problem in parsing. The problem is that :
I will give an example (not about google)
This is the class
Public Class MyModel
Dim m_tes As String
Dim m_client_list As String
Public Property type() As String
Get
Return m_tes
End Get
Set(ByVal value As String)
m_tes = value
End Set
End Property
Public Property client_list() As String
Get
Return m_client_list
End Get
Set(ByVal value As String)
m_client_list = value
End Set
End Property
End Class
and this is the JSON Deserializer
Dim deserializedProduct As MyModel = JsonConvert.DeserializeObject(Of MyModel)(JSON)
MsgBox(deserializedProduct.type)
MsgBox(deserializedProduct.client_list)
If I get one record Json data ,It works fine
like
dim JSON = {"type":"newModel","client_list":"Joe"}
The output of the msgbox is
newModel
Joe
The problem is that if I get a list of Json
I need a way to split this list likeh the following:
Json = {"type":"clientlist","client_list":"client 1"},{"type":"clientlist","client_list":"client 1"}
I haven't worked a whole lot with JSON, but I think you can pass a collection into the deserializer to get a back a collection of the deserialized objects.
In other words:
Dim deserializedProduct As List(Of MyModel) = JsonConvert.DeserializeObject(Of List(Of MyModel))(JSON)
The above code is similar to what you posted, except that is uses List<T> instead of a single instance of your MyModel object, and for the type used with the DeserializeObject you give it a List(Of ModelType).
Note that your MsgBox(deserializedProduct.type) and MsgBox(deserializedProduct.client_list) won't show you the results in a List<T> (you'll get the type name instead) - you'll need to loop through the list. Something like this:
For Each Dim model As MyModel In deserializedProduct
MsgBox(model.type)
MsgBox(model.client_list)
Next
Related
In VB.Net program I'm getting the "Cannot deserialize the current JSON array" when using JsonConvert.DeserializeObject(Of MCMusicElements)(sRB).
The JSON array I'm working with is:
[{"Key":465419,"MIK_Energy":3,"MIK_Camelot":"9B","MIK_BPM":118}]
If I delete the "[ ]" in the JSON string my program works. So, I'm assuming my Class definition for MCMusicElements is wrong in some way. I'd like to understand how to make it work without deleting the brackets from the JSON string.
Public Class MCMusicElements
Public Property Key As Integer
Public Property MIK_Energy As Integer
Public Property MIK_Camelot As String
Public Property MIK_BPM As Integer
End Class
Dim oResult = JsonConvert.DeserializeObject(Of MCMusicElements)(sRB)
dtDataTable.Rows(index).Item(1) = oResult.MIK_Energy
dtDataTable.Rows(index).Item(2) = oResult.MIK_Camelot
dtDataTable.Rows(index).Item(3) = oResult.MIK_BPM
you have to use list of objects, not an object
Dim oResult = JsonConvert.DeserializeObject(Of List(Of MCMusicElements))(sRB)
dtDataTable.Rows(index).Item(1) = oResult(0).MIK_Energy
This is the json data I am trying to parse. (I did trim the imagedata down for example purposes)
{"imageData":["SUkqAORlAACGniG0JCHeSTV9icwWxF+N9AwzcsTDlLu+PeYCgeZXAP//","sfsdfsdyfhh2h43h8ysdfsdnvjknjfdsfdsf"]}
Any idea on how to parse it into a strongly typed class in .NET?
I am using the newtonsoft.json
I tried the following
Public Class DAFGImages
Public imageData As List(Of String)
End Class
Dim DAFGImages As List(Of DAFGImages) = Newtonsoft.Json.JsonConvert.DeserializeObject(json, GetType(List(Of DAFGImages)))
Your class already contains a List of string, so you dont need a list of DAFGImages too. I would change the class member to a property:
Public Class DAFGImages
Public Property imageData As List(Of String)
End Class
Then:
Dim jstr = ... from wherever
Dim myImgs = Newtonsoft.Json.JsonConvert.DeserializeObject(Of DAFGImages)(jstr)
myImgs.ImageData will contain the 2 elements.
Hi there I have been messing with Azure Mobile Services recently and after solving one problem I have come up against another one. I have a stored procedure held on my Azure SQL db which is then invoked by a custom API on my Mobile service.
In my client I can call the API to return a JSON token (or array):
Dim result As Linq.JToken = Await App.subtlesoftClient.InvokeApiAsync("test1",
System.Net.Http.HttpMethod.Get, Nothing)
I then convert this into a json string:
Dim jString As String = result.ToString
Which gives me:
{[
{
"id": 2,
"message": "This is another test message cos everything is almost almost great but what can you do eh",
"messageDate": "2015-05-10T00:00:00Z"
}
]}
What I can't figure out is how to take the result and pass it into my class:
Public Class test1
Private _ID As Integer
Private _MessageDate As Date
Private _Message As String
<JsonProperty(PropertyName:="id")>
Public Property ID As Integer
Get
Return _ID
End Get
Set(value As Integer)
_ID = value
End Set
End Property
<JsonProperty(PropertyName:="message")>
Public Property Message As String
Get
Return _Message
End Get
Set(value As String)
_Message = value
End Set
End Property
<JsonProperty(PropertyName:="messageDate")>
Public Property MessageDate As Date
Get
Return _MessageDate
End Get
Set(value As Date)
_MessageDate = value
End Set
End Property
End Class
I have tried:
Dim myArray = result.Children(Of Linq.JProperty)().
FirstOrDefault(Function(x) x.Name = "").Value
To try and put it into an array I can enumerate through. This causes errors probably because I am not passing a name into the function as my json does not appear to have a name.
Ultimately the return json will be multiple objects so I want to be able to pass them into a MobileServiceCollection(Of MyType), and I don't know how. The documentation on this seems pretty scant.
Well thanks for giving me some pointers anyway seems it was very easy in the end, isn't it always when you figure it out:
Dim result = Await App.subtlesoftClient.InvokeApiAsync("test1", System.Net.Http.HttpMethod.Get, Nothing)
Dim jString As String = result.ToString
Dim myTest = JsonConvert.DeserializeObject(Of List(Of test1))(jString)
This works fine, seems the square brackets on the JSON string indicate its is an array.
I am just trying to figure out the best way to deserialize a json string returned from a 3rd party api call. I read ServiceStack is fast so want to try it out. No experience and here is what I have done:
Opened Visual Studio 2013
Created new project Windows Forms Application
Installed ServiceStack.Text (based on https://servicestack.net/download)
Added a button (btnView) and textbox (txtOutput)
Add code to btnView_Click event
Private Sub btnView_Click(sender As Object, e As EventArgs) Handles btnView.Click
Me.Cursor = Cursors.WaitCursor
Dim wp As New WebPost 'this allows to pass url and return results
wp.URL = "xxxx"
Dim sJSONRetVal As String = wp.Request(String.Empty, True)
'sJSONRetVal return values looks like the following:
'{"complaints":[{"feedback_type":"abuse","subject":"Sales Agent Position"},{"feedback_type":"abuse","subject":"Sales Agent Position"}],"message":"OK","code":0}
'ServiceStack.Text example
Dim t As SMTP_Complaints = ServiceStack.Text.JsonSerializer.DeserializeFromString(Of SMTP_Complaints)(sJSONRetVal)
'For Each xi As SMTP_Complaints In t
' txtOutput.Text &= xi.mail_from & vbCrLf
'Next
wp = Nothing
txtOutput.Text = t.ToString
Me.Cursor = Cursors.Default
End Sub
Public Class SMTP_Complaints
Dim _feedback_type As String = ""
Dim _subject As String = ""
Public Property feedback_type As String
Get
Return _feedback_type
End Get
Set(value As String)
_feedback_type = value
End Set
End Property
Public Property subject As String
Get
Return _subject
End Get
Set(value As String)
_subject = value
End Set
End Property
End Class
The above doesn't seem to get any data. how would I loop through the data returned and return the data from both instances? Just not sure how I need to set this up to read the json data and then be able to output.
Based on the returned JSON of:
{"complaints":[{"feedback_type":"abuse","subject":"Sales Agent Position"},{"feedback_type":"abuse","subject":"Sales Agent Position"}],"message":"OK","code":0}
You will need two DTOs to deserialise this result.
I have used auto implemented properties here to simplify the complexity of the code. If you use an older version of VB, you'll need to expand these out to include a backing field with get and set method.
Public Class SMTP_Complaint
Public Property feedback_type As String
Public Property subject As String
End Class
Public Class SMTP_ComplaintsResponse
Public Property complaints As SMTP_Complaint()
Public Property message As String
Public Property code As Integer
End Class
You need the SMTP_ComplaintsResponse class because your complaints are wrapped in your JSON response.
Then to deserialise the response:
Dim response = JsonSerializer.DeserializeFromString(Of SMTP_ComplaintsResponse)(sJSONRetVal)
And your complaints are then accessible:
For Each complaint As var In response.complaints
Console.WriteLine("Type: {0}, Subject {1}", complaint.feedback_type, complaint.subject)
Next
I have a simple JSON string that I am trying to parse with Visual Studio Express 2010 using native .net 4.0 instead of NewtonSoft. The json data that I am trying to parse looks like the following.
"{"token_type":"Bearer",""expires_in":3599,"access_token":"VxwK6YWYj6paqyMK2D2r4uDl34qg"}"
I can get the following code to run without error but when I try to dump the contents of the object I don't have any in the list. Here is the class I created.
Public Class AuthToken
Public Property token_type As String
Get
Return m_token_type
End Get
Set(ByVal value As String)
m_token_type = value
End Set
End Property
Private m_token_type As String
Public Property expires_in() As Integer
Get
Return m_expires_in
End Get
Set(ByVal value As Integer)
m_expires_in = value
End Set
End Property
Private m_expires_in As String
Public Property access_token As String
Get
Return m_access_token
End Get
Set(ByVal value As String)
m_access_token = value
End Set
End Property
Private m_access_token As String
End Class
My feeling is that my problem is in my class but I am not sure. So after looking for hours on this site and others Trouble parsing Json into .net Object I have put together the following code to parse the information and dump it to a RichTextBox just to see what it is.
Dim sr As New StreamReader(req.GetResponse.GetResponseStream)
Dim authtoken As New List(Of AuthToken)()
Dim ms As New MemoryStream(System.Text.Encoding.Unicode.GetBytes(sr.ReadToEnd))
Dim serializer As New System.Runtime.Serialization.Json.DataContractJsonSerializer(authtoken.GetType)
authtoken = DirectCast(serializer.ReadObject(ms), List(Of AuthToken))
ms.Close()
ms.Dispose()
sr.Close()
sr.Dispose()
For Each token In authtoken
rtbResponse.AppendText("Token: " & token.access_token & " Expires in: " & token.expires_in)
Next
So is my class created incorrectly? Is the data from the memorystream just not getting into the authtoken object because the class doesn't match the contents of the json data as it is deserialized?
If I am using the "DataContractSerializer" do I need to have data contract "stuff" in my class?
Any help is GREATLY appreciated.
The data is not getting into the authtoken variable because you don't have a list of auth tokens there - only one object. So if you get those JSON objects one at the time get rid of your lists and do it like that:
Dim sr As New StreamReader(req.GetResponse.GetResponseStream)
Dim authtoken As AuthToken
Dim ms As New MemoryStream(System.Text.Encoding.Unicode.GetBytes(sr.ReadToEnd))
Dim serializer As New System.Runtime.Serialization.Json.DataContractJsonSerializer(GetType(AuthToken))
authtoken = DirectCast(serializer.ReadObject(ms), AuthToken)
ms.Close()
ms.Dispose()
sr.Close()
sr.Dispose()
rtbResponse.AppendText("Token: " & authtoken.access_token & " Expires in: " & authtoken.expires_in)