How to write ArrayMap to JSON?

This ArrayMap in question is libgdx’s. I tried this,


text: {
				class: map,
				"3": "Once upon a time, there are 3 bees",
				"4": "One of them was so ugly, so the other two died",
				"5": "Left alone, the ugly bee suicided",
				"6": "THE END"
			}

My goal is only to read Map with both String key-value pair. “text” is a ArrayMap<String, String> field and “map” is class tag for ArrayMap.class.

I’m not sure that i fully understand what you are trying to accomplish but you could do


text: {
  class: "map",
  entries: {
    "3": "Once upon a time, there are 3 bees",
    "4": "One of them was so ugly, so the other two died",
    "5": "Left alone, the ugly bee suicided",
    "6": "THE END"
  }
}

You could then read the Class Property as normal Text-Value (Maybe use the real Class name -> could use Reflection to instanciate) and the entries as Map-Object, where you can then iterate over the Content and fill your ArrayMap Object with the Keys and Values.

The Json class can automatically serialize to/from POJOs, OrderedMap, Array, String, Float, and Boolean. It doesn’t know ArrayMap, so will treat it like a POJO, which isn’t quite what you want. In this case you’ll need to write a serializer that knows how to read/write ArrayMaps:

static public void main (String[] args) throws Exception {
	Json json = new Json();
	json.setSerializer(ArrayMap.class, new Json.Serializer<ArrayMap>() {
		public void write (Json json, ArrayMap map, Class knownType) {
			Object[] keys = map.keys;
			Object[] values = map.values;
			json.writeObjectStart();
			for (int i = 0, n = map.size; i < n; i++)
				json.writeValue(keys[i].toString(), values[i]);
			json.writeObjectEnd();
		}

		public ArrayMap read (Json json, Object jsonData, Class type) {
			ArrayMap map = new ArrayMap();
			for (Entry entry : ((OrderedMap<?, ?>)jsonData).entries())
				map.put(entry.key, entry.value);
			return map;
		}
	});
	json.addClassTag("map", ArrayMap.class);
	ArrayMap map = new ArrayMap();
	map.put("3", "Once upon a time, there are 3 bees");
	map.put("4", "One of them was so ugly, so the other two died");
	map.put("5", "Left alone, the ugly bee suicided");
	map.put("6", "THE END");
	String text = json.toJson(map);
	System.out.println(json.prettyPrint(text));
	ArrayMap map2 = json.fromJson(ArrayMap.class, text);
	System.out.println(map2);
}

If your “text” fields was an OrderedMap instead of ArrayMap, you wouldn’t have to do this (but of course these two map implementations are quite different).