VB.NET Deserialize JSON to anonymous object using newtonsoft returned error - vb.net

I would like to deserialize the returned JSON from a service call in VB.NET to an anonymous type but I was having error. It works in C# using dynamic type but i dont know how to do it in VB.
Here is my JSON returned from a web service call:
{"format":"png","height":564,"width":864}
Here is my VB code json above assigned to param text:
Dim testObj = Newtonsoft.Json.JsonConvert.DeserializeObject(text)
But when i tried to access testObj.format, an exception was thrown with message
{"Public member 'format' on type 'JObject' not found."}
I already have added Option Strict Off. I dont want to use an Object/Class to deserialize the JSON. If its in C# assigning this to dynamic type will be working fine.
Can anyone please help? I am not expert in VB but I need to have this running on VB. TIA

Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim testObj = js.Deserialize(source, New Object().GetType())
Then you can access the key(attribute name)/values via:
value=testobj(key)
One more thing, you can access your Newtonsoft key(attribute name)/values through:
value=testObj.item(key)

Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim DeSerialObjEventData = New With {.Prop1 = String.Empty, .Prop2 = String.Empty, .Prop3 = String.Empty}...
Dim testObj = js.DeserializeAnnonomusType(source, DeSerialObjEventData)

Related

VB.net Unable to cast object of type System.Collections.Generic.list to type string

Please forgive me in advanced for my lack of coding knowledge.
I'm using a NuGet package called KuCoin.Net and have everything setup and connected. I can run the command and Place a Buy order so I know my Api settings are correct. The issue I'm having is when I run the following code:
Public Async Function GetBalancesAsync() As Task
Dim kucoinClient = New KucoinClient(New KucoinClientOptions() With {
.ApiCredentials = New KucoinApiCredentials("xxx", "xxx", "xxx"),
.LogLevel = LogLevel.Debug,
.RequestTimeout = TimeSpan.FromSeconds(60),
.FuturesApiOptions = New KucoinRestApiClientOptions With {
.ApiCredentials = New KucoinApiCredentials("xxx", "xxx", "xxx"),
.AutoTimestamp = False
}})
Dim accountData = Await kucoinClient.SpotApi.Account.GetAccountsAsync()
MessageBox.show(accountData.data)
End Function
I guess I'm needing to convert the list to a string so I can display it into a Messagebox.
The Error I recieve is as follows:
Unable to cast object of type 'System.Collections.Generic.List`1[Kucoin.Net.Objects.Models.Spot.KucoinAccount]' to type 'System.String'
Here is some additional info if this helps
Error
accountData
Any help is much appreciated
You can generate your String yourself using a StringBuilder while enumerating through accountData.Data:
Dim sb As New System.Text.StringBuilder
For Each account As Kucoin.Net.Objects.Models.Spot.KucoinAccount In accountData.data
sb.AppendLine(account.ToString)
Next
MessageBox(sb.ToString())
You can change account.ToString to something more appropriate like accout.Number perhaps (see the properties the KucoinAccount object has).

How do I get the Kind of Elements in an Array using Roslyn

I am trying to get the Type that is iterated through using Roslyn. I can get the fact that the object is defined as String() using
Dim ElementTypeInfo As TypeInfo = SemanticModel.GetTypeInfo(ForEachStatement.Expression)
Dim expressionType As ITypeSymbol = ElementTypeInfo.Type
and in the Visual Studio debugger I can look at expressionType.ElementType and find out it is a String. But when I try to access ElementType in code I get an error saying the ElementType is not a member of ITypeSymbol.
If you know that expressionType is going to be an array, you can cast it to IArrayTypeSymbol. After that, you will be able to access its ElementType:
Dim expressionType = DirectCast(elementTypeInfo.Type, IArrayTypeSymbol)
Dim elementType As ITypeSymbol = expressionType.ElementType

Using JSON.NET instead of the default WebMethod serialization

In a WebMethod I am using JSON.NET to manually serialize my object to avoid the entity framework circular reference problem.
I have the following code:
Dim qry = From m In entity.Mediators _
Where m.MediatorNumber = mediatorNumber _
Select m
For Each mediator In qry
mediator.MediatorRestrictionsAvailabilities.Load()
customMediator = mediator
Next
customJson = JsonConvert.SerializeObject(customMediator, Formatting.Indented)
The problem is that the result is not well formatted JSON and cannot be parsed on the client; it looks like this:
{"d":"{\r\n \"$id\": \"1\",\r\n \"MediatorId\": 922,\r\n \"AreaCode\": \"E \",\r\n \"PFCCode\": \"840 \",\r\n \"FirstName\": \"Joe\",\r\n \"LastName\": \"Smith\",\r\n
After doing some research I have learned that this is what happens when JSON is reserialized into JSON.
How do I do my own custom serialization without the default serializer getting in the way?
I had a similar problem a while back and here are the suggestions which I was given. My solution was that I did not need to serialize the object again into json as it was already being serialized.
Good luck and hope this helps some.
For the circular reference use this approach:
string json = JsonConvert.SerializeObject(
infoToSerialize, Formatting.Indented,
new JsonSerializerSettings{ ReferenceLoopHandling =
ReferenceLoopHandling.Ignore
});

convert vb.net data to json string and send it to a specific URL

this is the JSON string the data is required in to be sent using a given URL.
$jsonstr = '{"data":
[{
"id":"5",
"owner_id":"0",
"status":"unassigned",
"first_name":"Test",
"last_name":"IS",
"tobacco_user":"",
"date_of_birth":"",
"age":"",
"gender":"",
"email":"lb#you.com",
"zip":"",
"phone":"(210)629-2560",
"phone_type":"cell",
"phone_alt":"",
"phone_alt_type":"",
"product_msip":"",
"product_pdp":"",
"product_sdhv":""
},
I am using VB.net and i need to create this string using VB.net. I tried using namevaluecollection and doing a POST. I also tried making a string and send data using GET. Both failed. how can i do this?
Create an object with property names that are identical to those in your example, use the DataContract and DataMember attributes to mark serialization.
Then use the JavaScriptSerializer to serialize the object into JSON.
you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.
If you don't want to build an actual class as #Oded recommended you can just hack it together as a string. I usually use a NameValueCollection as you said you tried.
''//Setup some values
Dim NVC As New NameValueCollection()
NVC.Add("id", "5")
NVC.Add("owner_id", "0")
NVC.Add("status", "unassigned")
''//Convert to string
Dim Pairs As New List(Of String)
For Each N As String In NVC.Keys
Pairs.Add(String.Format("""{0}"":""{1}""", N.Replace("""", "\"""), NVC(N).Replace("""", "\""")))
Next
Dim S = Join(Pairs.ToArray(), ",")
S now holds "id":"5","owner_id":"0","status":"unassigned" which you should be able to concat into your bigger JSON string.

Return more than a single value from a WebService

I have to return a lot of values back to my windows application from my webService. But how would I return more than just a single string/int/boolean from my WebService to my Application. How would I return a collection, keyValuePair, or even better, a DataSet? Or is this just imposible?
thank you :)
any serializable class can be returned from a web service
If your webservice is written in ASP.NET it's as simple as setting the return type from your webservice to be the more complex type. Most serializable types are supported.
The best method I've used with webservices is to return XML as a string. This way there are no compatability issues and parsing the XML is easy enough.
Along the same lines as returning XML, if you're returning to javascript code, you may want to consider returning your complex type as serialized in JSON.
Here is an extension method which makes this really easy...
<Extension()> Public Function ToJSON(Of T As Class)(ByVal target As T) As String
Dim serializer = New System.Runtime.Serialization.Json.DataContractJsonSerializer(GetType(T))
Using ms As MemoryStream = New MemoryStream()
serializer.WriteObject(ms, target)
ms.Flush()
Dim bytes As Byte() = ms.GetBuffer()
Dim json As String = Encoding.UTF8.GetString(bytes, 0, bytes.Length).Trim(Chr(0))
Return json
End Using
End Function
Then in your data service, you can simply call
Return MyObject.ToJSON