【问题标题】:Error convert json to datatable in vb.net在 vb.net 中将 json 转换为数据表时出错
【发布时间】:2013-10-22 11:54:59
【问题描述】:

我通过 http 接收以下字符串为 json:

 Dim json As String = "[{" + """name"":""jocelyne" + """," + """mo"":""jocelyne" + """}" + ",{" + """name"":""eliane" + """," + """mo"":""12345678" + """}" + "]"

我需要将此json数组转换为vb.net中的数据表

我尝试使用 NewtonSoft.json.dll :

Dim jss As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim deserializedProduct As Dictionary(Of String, String) = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(json)

但我不断收到当前位置没有可用的源代码,尽管我添加了对我的项目的引用并且它在 bin 文件中..

实际错误是:

Cannot deserialize JSON array into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]'.

有没有办法解决这个问题,或者是否有人有另一种方法可以将 json 数组转换为 vb.net 中的数据表?

【问题讨论】:

  • @Shruti json 中有什么不正确的地方?
  • 您可以使用此链接jsonlint.org 来验证您的 json
  • @Shruti 我的 json 是有效的 :)

标签: asp.net json vb.net datatable http-post


【解决方案1】:

您尝试将 JSON 字符串反序列化为应表示一个对象的 Dictionary,但您的 JSON 字符串包含一个由两个对象组成的数组,而不是一个对象。

所以你应该使用List(Of Dictionary(Of String, String)) 而不是Dictionary(Of String, String)

LINQPad:

Sub Main
    Dim json As String = "[{" + """name"":""jocelyne" + """," + """mo"":""jocelyne" + """}" + ",{" + """name"":""eliane" + """," + """mo"":""12345678" + """}" + "]"
    Dim deserializedProduct As List(Of Dictionary(Of String, String)) =  JsonConvert.DeserializeObject(Of List(Of Dictionary(Of String, String)))(json)
    deserializedProduct.Dump()
End Sub

如果你想要DataTable,只需使用

Sub Main
    Dim json As String = "[{" + """name"":""jocelyne" + """," + """mo"":""jocelyne" + """}" + ",{" + """name"":""eliane" + """," + """mo"":""12345678" + """}" + "]"
    Dim table As DataTable = JsonConvert.DeserializeObject(Of DataTable)(json)
    table.Dump()
End Sub

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-06-01
  • 2016-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多