Not sure if the title is quite correct - I've been doing a bit of digging on this and can't quite find a good answer. I've seen a couple of related questions, but I'm having trouble figuring out which solution will actually help and how to implement it.
I am trying to import a Json file that is being generated in a different language, and trying to figure out a way to read the data effectively. This is for a minecraft-esque world save system, using a set of chunks and blocks. Each block location is an int, with an ID assigned to it. The file looks like this (shortened):
[
{
"anchor": [
-128,
0,
-128
],
"blocks": {
},
"id": 0
},
{
"anchor": [
48,
0,
-112
],
"blocks": {
"1037": 10,
"1038": 10,
"1053": 10,
"1054": 10,
"1069": 10,
"1070": 10,
"1071": 10,
},
"id": 27
}
]
I can pull the anchor as an array of ints, and the id as a standalone int, but I'm having trouble pulling the list of blocks - What's the best way to import this data?
This is the class I had been using previously, before realizing that dictionaries don't function with jsonUtility:
public class Chunk
{
public int[] anchor;
public Dictionary<int, int> blocks;
public int id;
public Chunk(Vector3Int location, int newid)
{
blocks = new Dictionary<int, int>();
id = newid;
anchor = new int[] {location.x, location.z, location.y};
}
}
I've also tried a version using a List of generic objects to no avail.
And the importing process as a bare-bones json import:
string import = File.ReadAllText(saveDataLocation);
Chunk islandImport = JsonUtility.FromJson<Chunk>(import);
CodePudding user response:
The following works using Newtonsoft.Json:
public class Chunk
{
public int[] anchor;
public Dictionary<int, int> blocks;
public int id;
}
And then:
var chunks = Newtonsoft.Json.JsonConvert.DeserializeObject<Chunk[]>(json);
(I'm not sure how well this will translate to Untity.)
CodePudding user response:
Declare blocks type as JObject or dynamic. So you will not see any problem while deserializig.
Declare one more redyonly property to return the actual values of blocks property.
CodePudding user response:
Try this
public class Model
{
public List<int> anchor { get; set; }
public Dictionary<string, int> blocks { get; set; }
public int id { get; set; }
}
and use it with
JsonConvert.DeserializeObject<List<Model>>(myJson);