- Home /
The question is answered, right answer was accepted
Help using LitJson
Hello, i'm using LitJson on an app i'm currently working on.
I made a C# script wich will write a file, then i'll use the file on my app.
i can write the Json file, but not the way i want.
The way i'm making generates this output:
{"id":10,"texto":"OIOI","link":"Link","slug":"slug_","sub":"sub","nomedocampo":"nome","boolcheck":"ok"}
I wanted it to be an array, having the "[]" on each side of the Json file like this:
[{"id":10,"texto":"OIOI","link":"Link","slug":"slug_","sub":"sub","nomedocampo":"nome","boolcheck":"ok"}]
and here is my script wich writes the file:
using LitJson;
using System.IO;
using UnityEngine;
using System.Text;
public class Faz_Campos : MonoBehaviour
{
public int id = 10;
string texto = "OIOI";
string link = "Link";
string slug = "slug_";
string sub = "sub";
string nomedocampo = "nome";
string boolcheck = "ok";
public ECampos Ecampos = new ECampos(10, "OIOI", "link", "Slug_", "Sub", "nomedocampo", "ok");
JsonData EcamposJson;
void Start()
{
Ecampos = new ECampos(id, texto, link, slug, sub, nomedocampo, boolcheck);
EcamposJson = JsonMapper.ToJson(Ecampos);
File.WriteAllText(Application.persistentDataPath + "/StreamingAssets/campoos.json", EcamposJson.ToString());
}
}
public class ECampos //define um campo
{
public int id { get; set; }
public string texto { get; set; }
public string link { get; set; }
public string slug { get; set; }
public string sub { get; set; }
public string nomedocampo { get; set; }
public string boolcheck { get; set; }
public ECampos(int ID, string Texto, string Link, string Slug, string Sub, string Nomedocampo, string Boolcheck)
{
this.id = ID;
this.texto = Texto;
this.link = Link;
this.slug = Slug;
this.sub = Sub;
this.nomedocampo = Nomedocampo;
this.boolcheck = Boolcheck;
}
}
How do i make it work to write everything as an array?
I came up with a JSON serializer since Unity is not yet providing one.
https://unitygem.wordpress.com/json-serializer/
You need to add some attributes on the item you want to serialize and then you can use it like this:
ECampos campos = new ECampos();
// change some values on campos
JSONSerialize.Serialize(Path.Combine(Application.dataPath, "campos.json"), campos);
it takes care of any json type (object, item or array). It does not consider types like Quaternion or Rect which can be converted to Vector4...
Answer by Dave-Carlile · Dec 02, 2015 at 01:09 PM
Either put the object in an array and serialize the array... or add the brackets yourself?
"[" + EcamposJson.ToString() + "]";
How do you plan on loading the data back? It will have to be deserialized to an array if you save it as an array.
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
C# Convert json arrays to unity arrys 3 Answers
C# Converting json arrays using JsonUtility, 1 Answer
Importing from an external .txt file 2 Answers