2012-04-05 209 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