Is there no way to auto serialize any array with data to JSON?

using Gee;
public enum MyEnum {
    FOO, BAR, FOOBAR
}

public class MyObject : Object {
    public string str { get; set; }
    public MyEnum en  { get; set; }
    public int    num { get; set; }
    public ArrayList arr { get; set; }

    public MyObject (string str, MyEnum en, int num, ArrayList<int> arr) {
        this.str = str;
        this.num = num;
        this.en  = en;
        this.arr = arr;
    }
}

public static int main (string[] args) {
    var arr = new ArrayList<int>();
    arr.add(1);
    arr.add(6);

    MyObject obj = new MyObject ("my string", MyEnum.FOOBAR, 10, arr);
    string data  = Json.gobject_to_data (obj, null);
    print (data);
    return 0;
}

Output:

{
  "str" : "my string",
  "en" : 2,
  "num" : 10,
  "arr" : {
    "size" : 2
  }
}⏎

ArrayList is a Vala data type, so you’ll need to implement the JsonSerializable interface to tell json-glib how to serialise and deserialise it.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.