2017-03-03 48 views
0

我使用一個程序(瓷磚)創建一個遊戲,它吐出來的JSON文件tilesets與此類似:C#打開JSON爲數據

http://pastebin.com/t7UHzG7w

,我期待將其轉換成我可以使用的數據(「data」的地圖,或者「data」的int [] [],以及寬度/高度,所有其他信息都是無關的,我已經知道了)真的不知道該怎麼去做。

我該如何從該JSON轉換爲我可以處理的格式的數據?

回答

1

您應該使用創建模型類來表示您擁有的JSON數據。然後,您可以使用JavaScriptSerializer或Newsoft JOSN庫將此數據轉換爲對象。

你應該創建模型類爲您的數據:

public class Layer 
{ 
    public List<int> data { get; set; } 
    public int height { get; set; } 
    public string name { get; set; } 
    public int opacity { get; set; } 
    public string type { get; set; } 
    public bool visible { get; set; } 
    public int width { get; set; } 
    public int x { get; set; } 
    public int y { get; set; } 
} 

public class Tileset 
{ 
    public int columns { get; set; } 
    public int firstgid { get; set; } 
    public string image { get; set; } 
    public int imageheight { get; set; } 
    public int imagewidth { get; set; } 
    public int margin { get; set; } 
    public string name { get; set; } 
    public int spacing { get; set; } 
    public int tilecount { get; set; } 
    public int tileheight { get; set; } 
    public int tilewidth { get; set; } 
} 

public class Data 
{ 
    public int height { get; set; } 
    public List<Layer> layers { get; set; } 
    public int nextobjectid { get; set; } 
    public string orientation { get; set; } 
    public string renderorder { get; set; } 
    public int tileheight { get; set; } 
    public List<Tileset> tilesets { get; set; } 
    public int tilewidth { get; set; } 
    public int version { get; set; } 
    public int width { get; set; } 
} 

一旦做到這一點,你可以用Newtonsoft.Json庫字符串數據解析到這個對象。

string text = "<Your Json data>"; 
var result = JsonConvert.DeserializeObject<Data>(text); 

你可以從這裏下載Newtonsoft JSON庫:

http://www.newtonsoft.com/json

或者使用NPM還有:

安裝,包裝Newtonsoft.Json

+1

你認爲你能解釋多一點?也許一些語法?哪個更好,JavaScriptSerializer或Newsoft JSON庫? – user183106

1

你可以使用Newtonsoft.Json。然後之後你聲明你的對象/模型,你可以使用它像

string Json = ""; // your Json string 
var Result = JsonConvert.DeserializeObject<YourModel>(Json); 

爲了讓包,您可以使用Nugget功能和類型:

Install-Package Newtonsoft.Json