How to map an object to JSON in Processing

Hi all,

I’ve been looking into various ways of mapping object to json in Processing and I can’t seem to get anything to work.

I have tried GSON, Javax and Jackson. but all throw errors. Maybe I’m not loading all the dependencies I need.

Does anybody have a working example of object mapping to/from json in a processing sketch please?

1 Like

My theory is that you have to copy the values from the class into json value by value

here is an example


String[] species = { "Capra hircus", "Panthera pardus", "Equus zebra" };
String[] names = { "Goat", "Leopard", "Zebra" };

JSONArray values;

void setup() {

  size(320, 320);

  values = new JSONArray();

  for (int i = 0; i < species.length; i++) {

    JSONObject animal = new JSONObject();

    animal.setInt("id", i);
    animal.setString("species", species[i]);
    animal.setString("name", names[i]);

    values.setJSONObject(i, animal);
  }

  saveJSONArray(values, "data/new.json");
}

// Sketch saves the following to a file called "new.json":
// [
//   {
//     "id": 0,
//     "species": "Capra hircus",
//     "name": "Goat"
//   },
//   {
//     "id": 1,
//     "species": "Panthera pardus",
//     "name": "Leopard"
//   },
//   {
//     "id": 2,
//     "species": "Equus zebra",
//     "name": "Zebra"
//   }
// ]

This might have something useful: # JSON - how to get heirarchical names from file.