Convert JSon to dynamic object in VB.Net

为君一笑 提交于 2019-12-25 03:06:26

问题


I am using VB.Net and calling salesforce API. It returns very ugly JSON which I am not able to deserialize. I have a following code using JSON.Net

Dim objDescription As Object = JsonConvert.DeserializeObject(Of Object)(result)

objDescription contains many properties, one on=f them in fields. But when I write something like objDescription.fields it gives me error.

  objDescription.fields   Public member 'fields' on type 'JObject' not found. Object

I am not very sure but I think it C# allow to convert any JSON to dynamic object. How can I use it in VB.Net?


回答1:


You can turn Option Strict Off and use ExpandoObject which is recognized by JSON.NET. In order to leverage the dynamic features you can use a variable of type object.

Option Strict Off

Sub Main    
    Dim jsonData As Object = JsonConvert.DeserializeObject(Of System.Dynamic.ExpandoObject)("{""Id"":25}")
    Dim test As Integer = jsonData.Id
    Console.WriteLine(test)
End Sub

If you would like to use JObject because you need some of its features, you can index the JObject instead.

Sub Main
    Dim jsonData As Object = JsonConvert.DeserializeObject(Of Object)("{""Id"":25}")
    Dim test = jsonData("Id")
    Console.WriteLine(test)
End Sub


来源:https://stackoverflow.com/questions/49952858/convert-json-to-dynamic-object-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!