- Home /
SimpleJSON: how to store arrays??
using System;
using SimpleJSON;
using System.IO;
namespace JsonTets1
{
class Program
{
static void Main(string[] args)
{
int myInt = 32;
string myString = "Mamma mia!";
bool myBool = true;
int[] myIntArr = new int[3] { 1, 2, 3 };
bool[,] myBoolArr = new bool[2, 2] { { true, false }, { false, false } };
JSONNode j = JSONNode.Parse("{}");
j["int"] = myInt;
j["string"] = myString;
j["bool"] = myBool;
j["intArr"] = myIntArr; //error here >> Cannnot implicitly type 'int[]' to 'SimpleJSON.JSONNode'
j["boolArr"] = myBoolArr; //error here >> Cannnot implicitly type 'bool[*,*]' to 'SimpleJSON.JSONNode'
Console.Write(j.ToString());
using (StreamWriter f = new StreamWriter("new1.txt"))
{
f.Write(j.ToString());
}
}
}
}
I don't have much affinity with this library, I have tried to use it to save bool [,] and int [] data in a unity project, but i get the error you can read in the script above, so I created a simple script to study it more closely, but I still can't understand how to do it: I tried to create functions to encode arrays into strings and then decode them, but this is quite complex and inconvenient; Then I realized that there is a class called JSONArray, but the problem is the same, for the assignment a value of type JSONNode is required (apparently int, string and bool are implicitly converted); on the internet I found some solutions: Json.Deserialize, JsonConvert etc. None of these are compatible with my library. At the end, how do I store arrays in json?
Link to my Google Drive for Json libraries (in the script I only use the one called SimpleJSON): https://drive.google.com/drive/folders/1XIy9enfX41biQ7MBGStF4LG7yW9Ez6WY?usp=sharing
Answer by Bunny83 · Feb 09, 2021 at 03:33 AM
You have the wrong idea about how the library works ^^. Most json libraries are object mappers which work with POCOs. So you have to actually create an object structure in C# that represents the json object structure. SimpleJSON does not do object mapping to any POCO objects. It just represents the json object structure one to one with its own simple classes. So every value in the json text is represented through a JSONNode value. The implicit conversions only work for primitive types. So there is no direct conversion from a JSONArray to a native C# / .NET array. However you can of course copy the data yourself if you really need it in a native array.
Note that multidimensional arrays in .NET / C# have some limitations. They always need to be rectangular. Json does not have multi dimensional arrays but only jagged arrays. The problem is json can represent any multidimensional array but a multidimensional C# array may not necessarily be able to represent a json jagged array since the sub array are not required to have the same size.
So what you can do is something like this:
JSONNode j = new JSONObject();
j["int"] = myInt;
j["string"] = myString;
j["bool"] = myBool;
var intArr = j["intArr"].AsArray;
foreach(var val in myIntArr)
intArr.Add(val);
var boolArr = j["boolArr"].AsArray;
int size0 = myBoolArr.GetLength(0);
int size1 = myBoolArr.GetLength(1);
for (int i = 0; i < size0; i++)
{
var subArr = boolArr[-1].AsArray;
for (int j = 0; j < size1; j++)
{
subArr.Add(boolArr[i,j]);
}
}
Note that var subArr = boolArr[-1].AsArray;
is just a little trick to essentially do
var subArr = new JSONArray();
boolArr.Add(subArr);
The rest should be pretty straight forward. Note if you need to serialize / deserialize multi dimensional arrays a lot, of course you can implement your own conversion extension. However you would need to implement every required conversion yourself which is probably not worth the efford.
SimpleJSON is a simple and lightweight json library. You have full control over the structure and you are not bound to a certain class structure like you are with most object mappers.
Sorry for my ignorance about SimpleJSON library but the variable JSON j is an array? because you need to specify the element as int index [0].
j[index] = myIntArr[index];
JSONNode is a Type described in the SimpleJson library, it is like a list of KeyValuePair, which you can access by index (int) or by key (string) j[index] = myIntArr[index];
is technically ok but you will store the values one by one and this is inconvenient, also you need a JSONNode for each array and this makes everything more confusing and weighty
Ristoro$$anonymous$$atteo is right. The JSONNode represents just an abstract base class and provides a common interface to avoid the necessity to cast all the different types. The JSONArray class is a subclass of JSONNode which represents a json Array. Such an array has an internal List<JSONNode>
to store its members. Keep in $$anonymous$$d that in json you can have arbitrary supported subtypes. So an array in json can look like this:
[45, "FooBar", {"name":"some obj"}, ["sub array elm0", "sum array elm1"]]
So the types in s json array does not need to be the same but can be mixed. The JSONNode class has what is called an indexer. An indexer is a special kind of property that takes one or multiple "indices" of a certain type. As you might know a property is just a pair of get and set methods which are executed when you read or write to that property. So when we have a JSONNode j
which actually represents a JSONArray and we read j[2]
we actually call the getter of the indexer with the index "2". We get back another JSONNode that represents the element at this index of the JSONArray. This in turn could be any other JSONNode. There are several implicit type conversions implemented which make the usage less annoying. So there are type conversions for most common primitive types like string (JSONString), int, float, double (JSONNumber).and bool (JSONBool). There's also the special value JSONNull to represent null.
When you "request" a type conversion, it either directly returns the internal value or automatically tries to convert it. So you should never get an error. That means if you have a JSONNode that represents a JSONArray and you try to assign it to a float variable, you simply get the value "0". However if the actual value it a JSONString that represents a convertible number, it will parse the string as number and return that.
In the past there were only the conversion properties like float f = j[1].AsFloat;
They can still be used if you want to force a certain conversion or to make clear what type you want back.
Your answer
Follow this Question
Related Questions
Parsing JsonData throws error when value is null, what to do? 0 Answers
JSON-Serializer (Renewed open) 0 Answers
Whew, I'm stuffed! (Hunger Script) 1 Answer
C# - Read JSON 1 Answer
Application.ExternalCall Issue 0 Answers