2015-04-22 61 views
-1

所以,我正在開展一個學校項目,我正在試圖找出處理這個包含相當大量的JSON對象的數據文件的最佳方法。我知道VB.net的基礎知識,基本的事件處理等。如何使用VB.net解析此JSON?

我知道設計結構的基礎知識,以及類似的東西,但我需要弄清楚如何解析和創建一個5MB的對象列表JSON文件,該文件包含的條目,如下列:

{ 
    "Air Elemental":{ 
     "layout":"normal", 
     "name":"Air Elemental", 
     "manaCost":"{3}{U}{U}", 
     "cmc":5, 
     "colors":[ 
      "Blue" 
     ], 
     "type":"Creature — Elemental", 
     "types":[ 
      "Creature" 
     ], 
     "subtypes":[ 
      "Elemental" 
     ], 
     "text":"Flying", 
     "power":"4", 
     "toughness":"4", 
     "imageName":"air elemental" 
    }, 
    "Ancestral Recall":{ 
     "layout":"normal", 
     "name":"Ancestral Recall", 
     "manaCost":"{U}", 
     "cmc":1, 
     "colors":[ 
      "Blue" 
     ], 
     "type":"Instant", 
     "types":[ 
      "Instant" 
     ], 
     "text":"Target player draws three cards.", 
     "imageName":"ancestral recall" 
    }, 
    "Animate Artifact":{ 
     "layout":"normal", 
     "name":"Animate Artifact", 
     "manaCost":"{3}{U}", 
     "cmc":4, 
     "colors":[ 
      "Blue" 
     ], 
     "type":"Enchantment — Aura", 
     "types":[ 
      "Enchantment" 
     ], 
     "subtypes":[ 
      "Aura" 
     ], 
     "text":"Enchant artifact\nAs long as enchanted artifact isn't a creature, it's an artifact creature with power and toughness each equal to its converted mana cost.", 
     "imageName":"animate artifact" 
    } 
} 

如果任何人都可以提供幫助,或者只是有點點我在正確的方向,我會很感激。我認爲這扔我送行的大多數部分是每張卡的名字本身就是一個鍵,所有卡上的數據是一個名爲「鍵」相關聯的值...

回答

1

在這種情況下幾乎不成問題有多少,因爲它們都是結構相同的方式:

Public Class Spell 
    Public Property layout As String 
    Public Property name As String 
    Public Property manaCost As String 
    Public Property cmc As Integer 
    Public Property colors As String() 
    Public Property type As String 
    Public Property types As String() 
    Public Property subtypes As String() 
    Public Property text As String 
    Public Property power As String 
    Public Property toughness As String 
    Public Property imageName As String 
End Class 

我不知道什麼樣的數據表示,看起來有些奇幻遊戲。當反序列化(我用Newtonsoft),你將最終鍵爲「空元素」和「動畫神器」法術的字典等,但需要一行代碼:使用

Dim jstr As String = from whereever 
Dim mySpells = JsonConvert.DeserializeObject(Of Dictionary(Of String, Spell))(jstr) 

JavaScriptSerializer是差不多的:

Dim jss As New JavaScriptSerializer 
Dim myspells = jss.DeserializeObject(jstr) 

您可以使用http://jsonutils.com/,甚至VS選擇性粘貼,以幫助分析一下結構(類,真的)需要的樣子。然而,使用你的大腦並觀察它們是值得的。機器人將爲該JSON和另一個類容器創建3個類來保存它們。如果有100個這樣的話,那將是不必要的漫長。

由於每個項目都是相同的,並且每個JSON可以使用一個類。由於JSON格式適應,一個標準的NET字典工作正常。

+0

很酷,現在給它一個鏡頭。 – MisutoWolf

+0

所以,我試着去說,從閱讀這個文件生成的卡片字典的長度,我試圖解析,它似乎並沒有工作。代碼在這裏:http://pastebin.com/5EWVKTVL – MisutoWolf

+0

你不能一次反序列化一行。擺脫streamreader,只需使用'jstr = File.ReadAllText(datafile)' – Plutonix

1

有一個奇妙的功能中VS 2013在編輯菜單下調用了「粘貼爲JSON」,因此請複製您的JSON字符串並選擇此功能。

要知道,有我在,它宣稱陣列的方式MS報道了小蟲子。文本它可以讓你將

Public Property x() as DataType 

但是它需要改變

Public Property x as DataType() 

爲了正確地聲明爲數組。