如何用VB.NET读取一个不寻常的JSON文件

时间:2015-09-17 23:58:12

标签: .net json vb.net file json.net

我在vb.net中有一个应用程序,我正在尝试使用Json.Net读取.json文件。这就是我创建以下课程的原因:

Public Class Example
    Public Property minecraft.net As String
    Public Property session.minecraft.net As String
    Public Property account.mojang.com As String
    Public Property auth.mojang.com As String
    Public Property skins.minecraft.net As String
    Public Property authserver.mojang.com As String
    Public Property sessionserver.mojang.com As String
    Public Property api.mojang.com As String
    Public Property textures.minecraft.net As String
End Class

但它有几个问题,因为属性有点“。”

JSON格式如下:

[{"minecraft.net":"green"},{"session.minecraft.net":"green"},{"account.mojang.com":"green"},{"auth.mojang.com":"green"},{"skins.minecraft.net":"green"},{"authserver.mojang.com":"green"},{"sessionserver.mojang.com":"green"},{"api.mojang.com":"green"},{"textures.minecraft.net":"green"}]

我的问题是,如何创建类来阅读它?

1 个答案:

答案 0 :(得分:0)

这个特殊的JSON有点不寻常,因为它是一个对象数组,其中每个对象只有一个键值对,并且键在不同的对象之间变化。因此,您将无法将其反序列化为强类型类。相反,您可以将其反序列化为List(Of Dictionary(Of String, String)),如下所示。

Dim json As String = "[{""minecraft.net"":""green""},{""session.minecraft.net"":""green""},{""account.mojang.com"":""green""},{""auth.mojang.com"":""green""},{""skins.minecraft.net"":""green""},{""authserver.mojang.com"":""green""},{""sessionserver.mojang.com"":""green""},{""api.mojang.com"":""green""},{""textures.minecraft.net"":""green""}]"

Dim list As List(Of Dictionary(Of String, String)) = _
    JsonConvert.DeserializeObject(Of List(Of Dictionary(Of String, String)))(json)

For Each dict As Dictionary(Of String, String) In list
    Dim key As String = dict.Keys.First()
    Console.WriteLine(key & " = " & dict(key))
Next

小提琴:https://dotnetfiddle.net/RdcnJX