列表中的vb.net json + deserialise列表

时间:2015-02-11 03:48:26

标签: json vb.net

我正在使用json.net将json字符串反序列化为一个分类对象,以便在vb.net控制台应用程序中使用。我已经开始为每个字段设置类,但是我对如何设置sta类感到有点困惑,因为它看起来像是一个列表数组?

感谢您提供的任何帮助,计划是使用Json.JsonConvert.DeserializeObject将字符串反序列化到类中。我会错误处理,因为有些字符串没有任何笔画,只是时间。

{"time":1423625141,"id":35609390,"strokes":[{"time":1423625137180,"lat":-34.4798
08,"lon":147.249959,"alt":0,"cur":0,"dev":6553,"inv":0,"sta":[9,[812,849,919,118
5,874,1248,984,1276,875]],"id":35609386},{"time":1423625137250,"lat":-34.542924,
"lon":147.299573,"alt":0,"cur":0,"dev":7505,"inv":0,"sta":[9,[812,849,877,919,11
85,874,1248,984,1276,875]],"id":35609388},{"time":1423625137552,"lat":-34.514597
,"lon":147.284943,"alt":0,"cur":0,"dev":6894,"inv":0,"sta":[7,[849,919,1185,1248
,984,1276,1016,875]],"id":35609389}]}

我的班级如下:

Class Data
    Public time As Integer
    Public id As Integer
    Public strokes As List(Of Strokes)
End Class

Class Strokes
    Public time As Integer
    Public lat As Decimal
    Public lon As Decimal
    Public alt As Integer
    Public cur As Integer
    Public dev As Integer
    Public sta As New sta
End Class

Class sta
    Public sta As List(Of Integer)
End Class

1 个答案:

答案 0 :(得分:1)

即使您有通过JSON发送的复杂对象,DefaultModelBinder也应该将其拾取并将其映射到您的模型。但是,您需要确定一些事项。

首先是你如何发送你的JSON。内容类型应明确设置为“application / json”,如果使用JQuery,则需要使用$ ajax方法(而不是$ post),并确保stringify以正确格式化数据)。我还使用Fiddler来捕获JSON并通过在线验证器运行它以确保它传递的格式正确。

      $.ajax( {
        type: "POST",
        url: /MyJsonActionController',
        contentType: 'application/json; charset=utf-8',
        data: Json.stringify(MyFormData)
      }

其次,您的动作控制器应该简单地在构造函数Ex:

中声明要映射到的模型
    Public Function MyJsonActionController(ByVal d as Data) JsonResult
      'ModelBinder should do all of the work and then you can use the incoming model to do what you'd like
       SaveToDatabase(d)
       return Json(true)
    End Function

还要确保根据Model值名称命名表单字段。应该这样做。

如果遇到任何麻烦,这篇文章非常清楚地解释了ModelBinding的工作原理。您将看到,根据这篇文章,ModelBinder将首先读取所有基本类型以映射模型,如果有更复杂的类型,它将递归地再次传递并选择它们并映射它们。如果正确显示JSON,DefaultModelBinder实际上可以处理开箱即用的复杂/嵌套模型映射。

https://msdn.microsoft.com/en-us/magazine/hh781022.aspx