2012-04-05 86 views
0

我有一個看起來像這樣的JSON對象。將自定義JSON對象轉換爲VB.NET對象

{ 
"Errors":{ 
    "err1":[ 
    //* Array of err1 objects 
    ], 
    "err2":[ 
    //* Array of err2 objects 
    ] 
} 
} 

我使用此對象來報告在PHP頁面的請求中發現的錯誤。

我想那個對象轉換爲vb.Net對象聲明基本上是這樣的:

Public Class WebErrContainer 
    Public Errors as List(Of IWebError) 
End Class 

Public Class Err1 
    Implements IWebError 
End Class 

Public Class Err2 
    Implements IWebError 
End Class 

Public Interface IWebError 
End Interface 

我不知道如果我的實現是不夠好,我是比較新的VB.NET這樣我的OOP技能現在有點低。

就是這樣......我想我已經解釋了情況,以及我可以。

如果您需要更多信息,我會給它。

在此先感謝您提供的任何幫助。謝謝。

PD:我目前使用Newtonsoft的JSON.Net庫。隨意推薦一些其他庫或方法來處理VB.NET中的JSON。


我做這個解決情況:

Public Sub New(ByVal jsonText As String) 
    Dim jObject As JObject = jObject.Parse(jsonText) 
    Dim jErrors As JToken = jObject("Errors") 
    Dim jS = New JsonSerializer() 

    ' This is the "temporal" dictionary that stores the errors like they are 
    ' stored in JSON 
    Dim jsErrs As New Dictionary(Of String, List(Of Object)) 

    ' List that is going to be passed to the "Errors" field in the class 
    Dim lErrors As New List(Of IWebError) 



    jsErrs = jS.Deserialize(New JTokenReader(jErrors), jsErrs .GetType) 
    If Not jsErrs Is Nothing Then 
     For Each errType As KeyValuePair(Of String, List(Of Object)) In jsErrs 
      For Each Err As Object In errType.Value 
       lErrors .Add(jS.Deserialize(New JTokenReader(Err), Type.GetType(errType.Key))) 
      Next 
     Next 
    End If 
    Me.Errors = lErrors 
End Sub 
+0

我添加了一個解決方案,我出來了...請隨時報告代碼中發現的任何錯誤。 謝謝你的答案svick和Jayesh ... – saggio09 2012-04-05 17:04:59

回答

1

也許最簡單的解決方案是讓Errors成基於Err1Err2計算的只讀屬性:

Public Class WebErrContainer 
    Public Readonly Property Errors as List(Of IWebError) 
    Get 
     Return (Ctype(Err1, IEnumerable(Of IWebError))).Concat(Err2).ToList 
    End Get 
    End Property 

    Public Err1 as List(Of Err1) 
    Public Err2 as List(Of Err2) 
End Class 
+0

我不僅有兩種類型的錯誤,這個解決方案對我沒有幫助,我在主帖中發佈了一個解決方案。 – saggio09 2012-04-05 17:07:01

0

我認爲這可能會對你有所幫助。 這裏strJSON是您的JSON字符串

Dim jsS As New JavaScriptSerializer : objPostData = jsS.DeserializeObject(strJSON) 

之後,你可以重複這樣的

For Each objTop As Object In objPostData 
       objDic = CType(objTop, Generic.Dictionary(Of String, Object)) 
       dim strError as string = objDic.Item("Errors") 
Next 

我們如果什麼都想要

0

可你只需要使用反序列化來自動執行,我知道你,還是有什麼奇怪的事情發生。我已經使用了Newtsonsoft,並且我這樣做了(在c#中)

JsonConvert.DeserializeObject(Of MyJsonFromPHP)(jsonResponseText) 

Public Class MyJsonFromPHP 
    Public Property Errors as ErrorCollection 
End Class 

Public Class ErrorCollection 
    Public Property err1 As List(Of Err1) 
    Public Property err2 As List(Of Err2) 
End Class 

Public Class Err1 
    Public Property code as Integer 
    Public Property message as String 
End Class