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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| 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).