我正在尝试为内部应用程序反序列化以下JSON。
{
"resources": [
"output.ogg",
"output.m4a",
"output.mp3",
"output.ac3"
],
"spritemap": {
"click": {
"start": 0,
"end": 0.23034013605442177,
"loop": false
},
"CoinCMixed": {
"start": 2,
"end": 2.222448979591837,
"loop": false
},
"CoinDropMixed": {
"start": 4,
"end": 4.312222222222222,
"loop": false
}
}
}
我需要获得名称(例如"点击")以及start
和end
值。
问题是,名字并不总是一样的。它是独一无二的。所以,我猜我需要做的是循环通过spritemap
?但我不知道该怎么做。
例如:
- 名称:CoinDropMixed
- 开始:4
- 结束时间:4.3122222
这将允许我进行
msgbox("Your song name is " + Name + "The length is " + start + "The end is" + end)
您可以使用Dictionary
来处理不同的名称。这样定义你的类:
Class DataObject
Public Property resources As List(Of String)
Public Property spritemap As Dictionary(Of String, Sound)
End Class
Class Sound
Public Property start As Double
Public Property [end] As Double
Public Property [loop] As Boolean
End Class
然后,您可以像这样对JSON进行解密:
Dim data As DataObject = JsonConvert.DeserializeObject(Of DataObject)(json)
然后你可以像这样在字典上循环,以获得你想要的数据:
For Each kvp As KeyValuePair(Of String, Sound) In data.spritemap
Console.WriteLine("Name: " + kvp.Key)
Console.WriteLine("Start: " + kvp.Value.start.ToString())
Console.WriteLine("End: " + kvp.Value.end.ToString())
Console.WriteLine()
Next
Fiddle:https://dotnetfiddle.net/TxSy0i
如果名称是varibale,则很难使用反射来反序列化和检查对象。
同样,您的json格式不好,您需要一个根容器{}
{
"click": {
"start": 0,
"end": 0.23034013605442177,
"loop": false
},
"CoinCMixed": {
"start": 2,
"end": 2.222448979591837,
"loop": false
},
"CoinDropMixed": {
"start": 4,
"end": 4.312222222222222,
"loop": false
}
}
在这种情况下,手动解析json字符串可能是一个很好的解决方案。这是我的解决方案(未测试)
dim s as String = "JSON TEXT"
dim level as Integer = 0
dim stringStatus as Integer = 0
dim tmp as String =""
dim result as List(Of String) = new List(Of String)
for i as Integer =0 to (s.Length -1)
String c = s.Chars(i)
if c="{" then level = level +1
if c="}" then level = level -1
if (c="""" or c="'") and stringStatus = 0 then stringStatus = 1
elseif (c="""" or c="'") and stringStatus = 1 then
stringStatus = 0
if level = 1 then result.add(tmp)
tmp=""
elseif stringStatus = 1 then
tmp = tmp + c
end if
next
现在结果包含了你们的名字列表。。。。在此基础上,您可以为每个节点检索其他数据,如开始、结束、循环。。。