无法将当前JSON对象(例如{“name”:“value”})反序列化为类型'System.Collections.Generic.List`

时间:2015-07-25 16:01:07

标签: json vb.net

我知道在SO上已经有很多这样的问题,但这些答案都没有对我有用。我现在整天都在这里,而且我只是被炸了,所以这对JSON人来说很容易获胜。

错误是

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[FrozenSmoke.WorkflowDescription]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Path 'Workflows', line 1, position 13.

代码是(VB.NET)

Dim z As New List(Of WorkflowDescription)
z = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of WorkflowDescription))(ResponseStatus.Content)

这是我从服务器返回的JSON,它包含在ResponseStatus.Content中

{"Workflows":[{"GUID":"594d2946-7bee-49b3-b8bf-e5ee6715a188","Name":"ProcessElectronicContribution"},{"GUID":"fe368a11-2b79-41f9-bee9-edb031612365","Name":"AddActivist"},{"GUID":"4c552492-0014-439d-952b-aeb320e6d218","Name":"AddPartialActivist"}]}

这是班级

Public Class WorkflowDescription
Public Property Name As String = ""
Public Property GUID As String = ""
End Class

1 个答案:

答案 0 :(得分:2)

你的json不仅仅是一个数组/列表,而是一个包含Workflows属性的对象容器,它是一个列表/数组。

  

{&#34;工作流&#34;:[{&#34; GUID&#34;:....

工作流程是List / Array,但请注意它位于大括号内。那是&#34;外部容器&#34;。

Public Class WorkFlowContainer
    Public Property WorkFlows As List(Of WorkflowItem)
End Class

Public Class WorkflowItem
    Public Property Name As String
    Public Property GUID As String
End Class

json中的WorkFlows元素将映射到同名的属性。反序列化后,您可以删除容器:

' ultimate destination
Private myWorkFlows As List(Of WorkflowItem)
...
' elsewhere
Dim jstr = ... ` from whereever

' deserialize to the container
Dim wf = JsonConvert.DeserializeObject(Of WorkFlowContainer)(jstr)
' extract the list 
myWorkFlows = wf.WorkFlows

您可以忽略WorkFlowContainer,并在deseriazlizing中添加额外步骤:

Dim jstr = ... ` from whereever
Dim jopbj - JObject.Parse(jstr)

myWorkFlows = JsonConvert.DeserializeObject(Of List(Of WorkFlows))(jobj("Workflows"))

这样您就不必定义额外的类,也不必使用wf.来获取数据。

您可能知道大多数数组都可以反序列化为List或数组。要将Workflows定义为属性数组:

Public Property WorkFlows As WorkflowItem()