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.
Related
I,
i need to deserialize a sting that contain JSON formatted data but without root element
the data(simplified!) are this
[{"ID":"974",
"DataIns":"2022-08-12 14:13:26",
"NumeroFattura":"CTD18473",
"DataFattura":"2022-08-08",
"RagSocMit":"Example1"},
{"ID":"973",
"DataIns":"2022-08-12 13:31:00",
"NumeroFattura":"CTCC10189",
"DataFattura":"2022-08-08",
"RagSocMit":"Example2"},
{"ID":"971",
"DataIns":"2022-08-09 15:30:29",
"NumeroFattura":"C18474",
"DataFattura":"2022-08-08",
"RagSocMit":"Example2"}]
and the class for deserializing are this
Public Class TestClass
Public Property ID As String
Public Property DataIns As String
Public Property NumeroFattura As String
Public Property DataFattura As String
Public Property RagSocMit As String
End Class
If i try to deserialize with this code
Dim result As String = ""
Dim ListaFatture As FattureAC2
...
result = reader.ReadToEnd'contain the sting json from a WS
ListaFatture = JsonConvert.DeserializeObject(Of IEnumerable(Of FattureAC2))(result)
ListaFatture are equal to NOTHING
Someone can help me?
Tnx
Salvo
you can not deserialize as IEnumerable, you have to select what do you need an array or list for example
Dim ListaFatture As List (Of TestClass)
ListaFatture = JsonConvert.DeserializeObject(Of List(Of TestClass))(result)
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
I've a vb.net class that includes some serializable sub-classes
Public Class Model
<Serializable>
Public class foo
Public Property id as Integer
Public Property name as String
End Class
<Serializable>
Public Class bar
Public Property grading as Integer
Public Property minWage as Decimal
Public Property maxWage as Decimal
End Class
End Class
Now I receive from a web service, an object (as json formated string) and its class name (as string) and I'd like to Deserialize it as my object.
I could do, as it is actually working, a
Imports Newtonsoft.Json
Public Shared Function Deserialize(ByVal Json As String, ByVal name As String) As Object
Select Case name
Case "foo"
Return JsonConvert.DeserializeObject(of Model.foo)(Json)
Case "bar"
Return JsonConvert.DeserializeObject(of Model.bar)(Json)
End Select
End Function
But as you can imagine, I've a ton of classes, not just 2, so I tried to use Reflection
Imports System.Reflection
Imports Newtonsoft.Json
Public Shared Function Deserialize(ByVal Json As String, ByVal name As String) As Object
Dim assembly As Assembly = Assembly.GetAssembly(GetType(Model))
Dim type As Type = assembly.[GetType]("Model." & name) ' Why is this always Nothing?
Dim objInstance As Object = Activator.CreateInstance(type)
' objInstance = JsonConvert.DeserializeObject(Of ???)(Json)
Return objInstance
End Function
But on one hand the type variable is always Nothing, and on the other hand, I don't know what to put instead of the comment.
Can you please advise ?
You need to add the Namespace where the Model class is defined.
A nested class is separated by a +, so you have to add that to the full name of the Class object you want to create.
The composed string is then "[Namespace].[ClassName]+[NestedClassName]"
You don't need to create the instance, the Json Serializer will do that for you. Pass the Type of the class to the JsonConvert.DeserializeObject() method that accepts a Type as the second parameter.
Public Shared Function Deserialize(Json As String, className As String) As Object
Dim asm = Assembly.GetAssembly(GetType(Model))
Dim t As Type = asm.GetType($"{asm.GetName().Name}.Model+{className}")
Return JsonConvert.DeserializeObject(Json, t)
End Function
How you're going to use this, it's up to you :)
More generic:
Public Shared Function Deserialize(Of T)(Json As String, className As String) As Object
Dim asm = Assembly.GetAssembly(GetType(T))
Dim t1 As Type = asm.GetType($"{asm.GetName().Name}.{GetType(T).Name}+{className}")
Return JsonConvert.DeserializeObject(Json, t1)
End Function
Call as:
Dim deserialized = Deserialize(Of Model)(Json, "foo")
I've partially solve my problem, I can now crerate the right object, like so
Dim objType As Type = (From asm In AppDomain.CurrentDomain.GetAssemblies() From type In asm.GetTypes() Where type.IsClass AndAlso type.Name = name Select type).Single()
Dim objInstance As Object = Activator.CreateInstance(objType)
This is my final, working function, thanks to Jimi!
Public Shared Function Deserialize(ByVal Json As String, ByVal name As String) As Object
Try
Dim objType As Type = (From asm In AppDomain.CurrentDomain.GetAssemblies() From type In asm.GetTypes() Where type.IsClass AndAlso type.Name = name Select type).Single()
Return JsonConvert.DeserializeObject(Json, objtype)
Catch ex As Exception
Throw New Exception("Unknown class")
End Try
End Function
First question asked here, it is nice to be part of a coding community!
Currently I am retrieving a JSON string from an API and the response is as follows:
[{"playerId":37067559,"championId":78,"championLevel":5,"championPoints":93023,"lastPlayTime":1454133232000,"championPointsSinceLastLevel":71423,"championPointsUntilNextLevel":0},{"playerId":37067559,"championId":105,"championLevel":5,"championPoints":39025,"lastPlayTime":1454130615000,"championPointsSinceLastLevel":17425,"championPointsUntilNextLevel":0},{"playerId":37067559,"championId":81,"championLevel":5,"championPoints":37068,"lastPlayTime":1454273384000,"championPointsSinceLastLevel":15468,"championPointsUntilNextLevel":0}]
I set the string to be "response2"
Dim response2 As String = serviceRequest.DownloadString(New Uri(Mastery))
However in using the JavaScriptSerializer the code exits my console
Dim jss As New JavaScriptSerializer()
Dim model As MyModel = jss.Deserialize(Of MyModel)(response2)
Console.Write(model.championId(0))
Console.ReadLine()
I set the model for the Deserializer aswell
Public Class MyModel
Public Property playerId() As String
Public Property championId() As String
Public Property championPoints() As String
Public Property lastPlayTime() As String
Public Property championPointsSinceLastLevel() As String
Public Property championPointsUntilNextLevel() As String
End Class
However on startup the console exits itself. I'm not sure if I'm supposed to use model.championId(0) aswell, I assume to becuase there is more than one set of championId.
You need array of MyModel to hold the serialized objects
Try this (comment in code):
Dim jss As New JavaScriptSerializer()
' use model() to hold aray of MyModel
Dim model() As MyModel = jss.Deserialize(Of MyModel())(response2)
'As model is now array of MyModel you should use model(0), model(1) etc...
Console.Write(model(0).championId())
I'm not very good at this yet, not sure if my subject even accurately describes what I need. I know it's probably been answered, I'm having a hard time understanding the answers since they don't directly apply to my data. I am trying to figure out how I can iterate through the data in this URL.
http://tmi.twitch.tv/group/user/twitch/chatters
This is what I've been using.
Dim url = "http://tmi.twitch.tv/group/user/" & ConnectionInformation.Channel.TrimStart("#") & "/chatters"
Dim json As String = Nothing
Dim wc As New WebClient()
json = wc.DownloadString(url)
Dim root As JToken = JToken.Parse(json)
For Each item As JToken In root("chatters")
'I've tried several things here and I can't find a good way to iterate through the viewers found here.
Next
I guess I'm having trouble getting the viewers in a collection so that I can iterate through them, can someone point me in the right direction here?
Thank you.
"Chatters" is actually a Type in the root object. If you were to create classes, they would look like this:
Public Class RootChatter
Public Property _links As _Links
Public Property chatter_count As Integer
Public Property chatters As Chatters
End Class
Public Class _Links
End Class
Public Class Chatters
Public Property moderators As String()
Public Property staff As String()
Public Property admins As String()
Public Property global_mods As String()
Public Property viewers As String()
End Class
Viewers is an array in the Chatters Property (Root.Chatters.Viewers). Without the class:
Dim root As JToken = JToken.Parse(jstr)
Dim chatters = root("chatters")("viewers")
For n As Integer = 0 To chatters.Count - 1
Console.WriteLine(chatters(n))
Next
Output:
04paynem
0morningstar0
0rchlann
0riginus
10108abc
If you were to deserialize to the classes:
Dim jc = JsonConvert.DeserializeObject(Of RootChatter)(jstr)
Dim viewers = jc.chatters.viewers