【发布时间】:2017-10-28 14:28:12
【问题描述】:
我接受了一项有点困难的任务。我正在尝试获取一些 JSON 信息,但是,我不断收到无法反序列化当前 JSON 对象错误
这是我的代码
Public Class Rootobject
Public Property TextureAtlas As List(Of Subtexture)
End Class
Public Class Textureatlas
Public Property SubTexture() As Subtexture
Public Property _imagePath As String
End Class
Public Class Subtexture
Public Property _name As String
Public Property _x As String
Public Property _y As String
Public Property _width As String
Public Property _height As String
End Class
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim deserialized = JsonConvert.DeserializeObject(Of Rootobject)(RichTextBox1.Text.ToString())
For Each item In deserialized.TextureAtlas
MsgBox(item._name)
Next
这是错误
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[XMLPrasers.Form1+Subtexture]' because the type requires a JSON array (e.g.
这是 JSON
{
"TextureAtlas": {
"SubTexture": [
{
"_name": "AFKClick",
"_x": "0",
"_y": "0",
"_width": "82",
"_height": "82"
},
{
"_name": "AFKDef",
"_x": "84",
"_y": "0",
"_width": "82",
"_height": "82"
},
{
"_name": "AFKHover",
"_x": "168",
"_y": "0",
"_width": "82",
"_height": "82"
},
{
"_name": "BagClick",
"_x": "0",
"_y": "84",
"_width": "82",
"_height": "82"
},
{
"_name": "BagDef",
"_x": "84",
"_y": "84",
"_width": "82",
"_height": "82"
},
{
"_name": "BagHover",
"_x": "0",
"_y": "168",
"_width": "82",
"_height": "82"
},
{
"_name": "PetClick",
"_x": "84",
"_y": "168",
"_width": "82",
"_height": "82"
},
{
"_name": "PetDef",
"_x": "168",
"_y": "84",
"_width": "82",
"_height": "82"
},
{
"_name": "PetHover",
"_x": "168",
"_y": "168",
"_width": "82",
"_height": "82"
},
{
"_name": "ShopClick",
"_x": "252",
"_y": "0",
"_width": "82",
"_height": "82"
},
{
"_name": "ShopDef",
"_x": "252",
"_y": "84",
"_width": "82",
"_height": "82"
},
{
"_name": "ShopHover",
"_x": "336",
"_y": "0",
"_width": "82",
"_height": "82"
},
{
"_name": "TwitterClick",
"_x": "252",
"_y": "168",
"_width": "82",
"_height": "82"
},
{
"_name": "TwitterDef",
"_x": "336",
"_y": "84",
"_width": "82",
"_height": "82"
},
{
"_name": "TwitterHover",
"_x": "420",
"_y": "0",
"_width": "82",
"_height": "82"
}
],
"_imagePath": "Button.png"
}
}
【问题讨论】:
-
你的课错了。如果 JSON 中有很多根对象,则根对象应该只是
Public Property TextureAtlas As TextureAtlas,反序列化为RootObjects(坏名)的列表或数组。此外,TextureAtlas.SubTexture应该是一个列表或数组。错误消息的其余部分会告诉您有关数组/列表不匹配的信息。