我需要一些帮助。我想制作一个程序使用网站搜索数据,那些文本是JSON格式,我如何加载这些文件并将其写在标签上?
像这样> {"mature":null,"status":"Chill","broadcaster_language":"en","display_name":"MexxHD","game":"Counter-Strike: Global Offensive"}}
以下是我用于阅读此链接的链接> https://api.twitch.tv/kraken/channels/MexxHD
我能够从网站上得到一个“答案”,但我不知道如何在标签上打印它们(这是我使用的代码)
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://api.twitch.tv/kraken/channels/" & TextBox1.Text), HttpWebRequest)
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream())
我如何从这> { “成熟”:空, “状态”: “大寒”, “broadcaster_language”: “恩” .. 将Labe1.text等标签中的信息移动到Chill,将label2.text移动到en ...
答案 0 :(得分:1)
JSON字符串不仅仅是一个复杂的字符串 - 它是序列化数据(类,字典,数组等)。你也不能忽视你不关心的部分:你的帖子最后会留下一大块。
在这种情况下,看起来它可以被反序列化为Dictionary,最后一个元素(“_links”)本身就是一个字典。查看文本,第一个元素(“成熟”)为null,因此我使用Dictionary(Of String, Object)
:
Imports Newtonsoft.Json
' I downloaded it for ease, you could use the response
Dim json = File.ReadAllText("C:\Temp\MexxHD.json")
Dim col As Dictionary(Of String, Object)
col = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(json)
真的是这样的。显示内容(请记住至少有一个值为Nothing
):
For Each kvp As KeyValuePair(Of String, Object) In col
Console.WriteLine("Key: {0}, value: {1}", kvp.Key,
If(kvp.Value Is Nothing, "Null", kvp.Value.ToString))
Next
输出:
关键:成熟,价值:空白 关键:状态,价值:寒冷
关键词:broadcaster_language,value:en
键:display_name,值:MexxHD
(等)
链接部分可以反序列化为自己的字典:
Dim JLinks = col("_links").ToString
Dim linkCol As Dictionary(Of String, String)
linkCol = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(JLinks)
Console.WriteLine("********* LINKS ********* ")
For Each kvp As KeyValuePair(Of String, String) In linkCol
Console.WriteLine("K: {0} V: {1}", kvp.Key, kvp.Value)
Next
输出:
*********链接*********
K:自我V:https://api.twitch.tv/kraken/channels/mexxhd
K:跟随V:https://api.twitch.tv/kraken/channels/mexxhd/follows
K:商业V:https://api.twitch.tv/kraken/channels/mexxhd/commercial
(等)
当JSON看起来是一个类对象数组时,有一些在线工具可以从JSON字符串创建类结构,例如this one which will do VB classes
只需从词典中获取您想要的项目。请记住,某些值可以是Nothing
,就像“成熟”的情况一样,这可能会导致NullReference Exception:
Label1.Text = col("status").ToString()
答案 1 :(得分:-1)
首先这样做
Imports Newtonsoft.Json.Linq
第二次添加参考> Newtonsoft.Json.dll
并且第三次使用此代码
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("replace with your WEB LINK, HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim jResults As JObject = JObject.Parse(rawresp)
'===============LABELS TEXT===========================
Label1.Text = jResults(" replace with your token ").ToString()
最后一个,替换为您的信息