Op De Cirkel Op De Cirkel - 3 months ago 42
Java Question

JSON Representation of Map with Complex Key

I want to serialize to JSON the following (java) data structure:

class Machine {
String name;
Map<PartDescriptor, Part> parts;
}

class PartDescriptor {
String group;
String id;

hashCode()
equals()
}

class Part {
String group;
String id;
String description;
String compat;
...
...
}


What would be JSON representation of one
Machine
?

Also (optional), point me to a JSON to Java serializer/deserializer that will support your representation

Answer

I'd do something like:

{
  "name": "machine name",
  "parts": [
     { "group": "part group", "id": "part id", "description": "...", ... },
     { "group": "part group", "id": "part id", "description": "...", ... },
     // ...
  ]
}

If the "id" for each Part is unique, then the "parts" property can be an object instead of an array, with the "id" of each part serving as the key.

{
  "name": "machine name",
  "parts": {
     "1st part id": { "group": "part group", "description": "...", ... },
     "2nd part id": { "group": "part group", "description": "...", ... },
     // ...
  }
}
Comments