如何从该JSON文件中提取2D数组? [英] How can I pull the 2D array out of this JSON file?

查看:110
本文介绍了如何从该JSON文件中提取2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to know how to pull the 2D array out of the below JSON file. I am using Unity and would ideally like to use 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.

This is not a duplicate question as it deals with the unique case of having a nested array within the JSON file, and in particular I would like to use Newtonsoft.JSON.

推荐答案

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

If you want to use Newtonsoft (and pretty much any other JSON library), you'll just need to create a class to hold the deserialized object:

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
}

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

Then deserialize the string into your object:

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();
}

这篇关于如何从该JSON文件中提取2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆