Visual basic and Json.net Web request

爷,独闯天下 提交于 2019-12-02 03:16:53

One way to handle this would be to get the item into a Dictionary where the keys are the property names.

The class you have is not quite right unless you only want name and id and not the rest of the information. But using a Dictionary you wont need it anyway. The "trick" is to skip over the first part since you do not know the name. I can think of 2 ways to do this, but there are probably more/better ways.

Since json uses string keys pretty heavily, create a Dictionary, then get the data from it for the actual item:

jstr = ... from whereever
' create a dictionary
Dim jResp = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jstr)

' get the first/only value item
Dim jobj = jResp.Values(0)         ' only 1 item

' if you end up needing the name/key:
'Dim key As String = jResp.Keys(0)

' deserialize first item to dictionary
Dim myItem = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jobj.ToString)

' view results
For Each kvp As KeyValuePair(Of String, Object) In myItem
    Console.WriteLine("k: {0}  v: {1}", kvp.Key, kvp.Value.ToString)
Next

Output:

k: id v: 273746
k: name v: Chuck Noland
k: profileIconId v: 662
k: summonerLevel v: 30
k: revisionDate v: 1434821021000

Using String, String may also work, but it would convert numerics to string (30 becomes "30") which is usually undesirable.

While poking around I found another way to get at the object data, but I am not sure if it is a good idea or not:

' parse to JObject
Dim js As JObject = JObject.Parse(jstr)
' 1 =  first item; 2+ will be individual props
Dim jT As JToken = js.Descendants(1)

' parse the token to String/Object pairs
Dim myItem = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jT.ToString)

Same results.

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