Reputation: 801
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,
}
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.
Upvotes: 0
Views: 847
Reputation: 3058
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();
}
Upvotes: 2
Reputation: 364
If Unity supports dynamic keyword which comes with c# 4, then you can just assign it directly with
dynamic obj = JsonConvert.DeserializeObject(jsonData);
You will then access it directly: obj.layers.data
If the included mono framework doesn't support dynamic keyword, what you can do is create a model of the data which is a simple class with all the attributes and assign it in a similar fashion.
YourModel obj = JsonConvert.DeserializeObject<YourModel>(jsonData);
Upvotes: 0