2016-05-26 65 views
0

我有一個問題,我不知道如何解決。JSON JsonConvert.DeserializeObject錯誤

我試圖解決錯誤:

Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'name.jsonPrjData' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly

我發現對堆棧溢出類似的網頁,並試圖什麼的答案中提出的,但我無法弄清楚是什麼問題。

Imports Newtonsoft.Json 
Imports Newtonsoft.Json.Linq 

    Public Class jsonPrjData 
     Public Property sapcode() As String 
     Public Property prjCode() As String 
     Public Property prjDescript() As String 
    End Class 

    Public Class Form1 

     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 

     End Sub 

     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
      Dim webClient As New System.Net.WebClient 
      Dim result As String = webClient.DownloadString("http://localhost/json/") 
      Dim obj = JsonConvert.DeserializeObject(Of jsonPrjData)(result) 
     End Sub 
    End Class 

而且JSON看起來是這樣的:

[{"sapcode":"xxxx","prjCode":"xxxx","prjDescript":"xxxx"},{"sapcode":"xxxx","prjCode":"xxxx","prjDescript":"xxxx"}]

+1

我認爲它是因爲您試圖將一個json對象數組反序列化爲一個jsonPrjData .NET對象。你需要desirialize到一個集合或列表。 – yardpenalty

+0

我該怎麼做? – Starlays

回答

2

錯誤消息的關鍵部分是:Cannot deserialize the current JSON array (e.g. [1,2,3])。該消息滾動給出一個清晰的概念做的:

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

方括號表示的數據是一個數組(例如,[1,2,3])和也是事實,即有明顯的2個重複的數據的集那裏有相同的結構。所以:

' Note the added() 
Dim prjData = JsonConvert.DeserializeObject(Of jsonPrjData())(result) 

隨着錯誤消息的後半部分表示,也可以反序列化到List(of T)

Dim prjList = JsonConvert.DeserializeObject(Of List(Of jsonPrjData))(result) 

當然由於目標對象是本地聲明,他們將只存在於那點擊事件。