【发布时间】:2017-03-03 04:53:26
【问题描述】:
我正在使用一个程序 (Tiled) 为游戏创建图块集,它会输出类似于以下内容的 JSON 文件:
我希望将其转换为我可以使用的数据(“数据”的映射,或“数据”的 int[][],以及宽度/高度等info 是无关的,我已经知道了),并且真的不知道该怎么做。
如何从 JSON 转换为我可以处理的格式的数据?
【问题讨论】:
我正在使用一个程序 (Tiled) 为游戏创建图块集,它会输出类似于以下内容的 JSON 文件:
我希望将其转换为我可以使用的数据(“数据”的映射,或“数据”的 int[][],以及宽度/高度等info 是无关的,我已经知道了),并且真的不知道该怎么做。
如何从 JSON 转换为我可以处理的格式的数据?
【问题讨论】:
您应该使用创建模型类来表示您拥有的 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
【讨论】:
【讨论】:
您可以使用Newtonsoft.Json。然后在你声明你的对象/模型之后,你可以像这样使用它
string Json = ""; // your Json string
var Result = JsonConvert.DeserializeObject<YourModel>(Json);
要获取包,您可以使用Nugget 函数并输入:
Install-Package Newtonsoft.Json
【讨论】: