JSON.Net - 读取/解析JSON行的文件

时间:2014-04-09 23:30:42

标签: .net vb.net json.net

我的输入如下:

[
{
"somenums": "1",
"someDate": "1.1.2014",
"viewdata": "1119958",
"visitdata": "152452",
"uniquedata": "125873"
},
{
"somenums": "2",
"someDate": "2.1.2014",
"viewdata": "1863752",
"visitdata": "241453",
"uniquedata": "200762"
}
]

我无法找到很多关于如何处理包含多行的文件。我发现的一小部分信息是Json会将方括号中的对象反序列化为List。

在摸索语法错误后,我最终得到了下面的代码,但在语句jrrows = DirectCast(JsonConvert.等上获得了运行时InvalidDirectCast异常。

    If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then

        My.Settings.LastJsonFileDirectory = Path.GetDirectoryName(ofd.FileName)
        My.Settings.Save()

        Dim sr As New StreamReader(ofd.FileName)
        Dim jrrows As List(Of JsonRow)
        jrrows = DirectCast(JsonConvert.DeserializeObject(sr.ReadToEnd), List(Of JsonRow))


    End If
End Sub
End Class

<Serializable()> _
Public Class JsonRow

    Public somenums As String
    Public someDate As String
    Public viewdata As String
    Public visitdata As String
    Public uniquedata As String

    Sub New()  'we need a parameter-less constructor to make it serializable
    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

在C#...

string json=File.ReadAllText(ofd.FileName);
List<JsonRow> mydata = JsonConvert.Deserialize<List<JsonRow>>(json);

在VB.NET(自动翻译)

Dim json As String = File.ReadAllText(ofd.FileName)
Dim mydata As List(Of JsonRow) = JsonConvert.Deserialize(Of List(Of JsonRow))(json)