如何从此JSON文件中提取2D数组?

时间:2018-02-02 11:48:12

标签: c# arrays json unity3d

我想知道如何从下面的JSON文件中提取2D数组。我正在使用Unity,理想情况下喜欢使用Newtonsoft.Json

{ "height":8,
 "infinite":false,
 "layers":[
        {
         "data":[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
         "height":8,
         "name":"Tile Layer 1",
         "opacity":1,
         "type":"tilelayer",
         "visible":true,
         "width":8,
         "x":0,
         "y":0
        }],
 "nextobjectid":1,
 "orientation":"orthogonal",
 "renderorder":"right-down",
 "tiledversion":"1.1.2",
 "tileheight":64,
}

这不是一个重复的问题,因为它处理在JSON文件中有嵌套数组的独特情况,特别是我想使用Newtonsoft.JSON。

4 个答案:

答案 0 :(得分:2)

如果你想使用Newtonsoft(以及几乎任何其他JSON库),你只需要创建一个类来保存反序列化的对象:

public class Layer
{
    public IEnumerable<int> Data {get;set;}
    public int Height {get;set;}
    // ... implement other properties
}

public class MyObject
{
    public int Height {get;set;}
    public bool Infinite {get;set;}
    public IEnumerable<Layer> Layers {get;set;}
    // ... implement other properties
}

然后将字符串反序列化为您的对象:

using Newtonsoft.Json.JsonConvert;
....
var myObject = DeserializeObject<MyObject>(jsonString);
foreach (var layer in myObject.Layers)
{
    // do something with each layer, e.g. get the sum of the data
    var sum = layer.data.Sum();
}

答案 1 :(得分:0)

此链接可能对您有所帮助。 JSONObject

答案 2 :(得分:0)

如果Unity支持c#4附带的动态关键字,那么您可以直接使用

分配它
dynamic obj = JsonConvert.DeserializeObject(jsonData);

然后,您将直接访问它:obj.layers.data

如果包含的单声道框架不支持动态关键字,你可以做的是创建一个数据模型,这是一个包含所有属性的简单类,并以类似的方式进行分配。

YourModel obj = JsonConvert.DeserializeObject<YourModel>(jsonData);

答案 3 :(得分:0)

你没有2D数组,你有一个包含数组的对象数组。没什么2D。

首先获取与json匹配的c#对象:

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

public class RootObject
{
    public int height;
    public bool infinite;
    public List<Layer> layers;
    public int nextobjectid;
    public string orientation;
    public string renderorder;
    public string tiledversion;
    public int tileheight;
}

使用转换器:

RootObject ro = JsonUtility.FromJson<RootObject>(json);
相关问题