I get a List like this, one Object per row holding plain strings:
Vehicle, Name, Property, Value
------------------------------
Car, VW, Tires, 4
Car, VW, Doors, 4
Car, Porsche, Tires, 4
Car, Porsche, Doors, 2
Car, Porsche, Color, Red
Plane, A340, Tires, 12
Plane, A340, Color, White
Plane, A750, Doors, 6
Forklift, ABC345, Color, Orange
... and so on
I want to return that as JSON in the form of:
{
"Car" : {
"VW":{ "Tires" : "4", "Doors": "4"},
"Porsche":{ "Tires" : "4", "Doors": "2" }
},
"Plane":{
"A340":{ "Tires" : "12", "Color" : "White" },
"A750":{ "Doors" : "6" }
},
"Forklift" : {
"ABC345": { "Color" : "Orange" }
}
}
I tried using a weird
HashMap<String, HashMap<String, HashMap<String, String>>>
but to be honest, I don't know how to set this up correctly. When I iterate over the list and write to the HashMap, Property and Value always get overwritten, so my result looks like this:
{
"Car" : {
"Porsche":{ "Tires" : "4" }
},
"Plane":{
"A750":{ "Doors" : "6" }
},
"Forklift" : {
"ABC345": { "Color" : "Orange" }
}
}
I'm fairly new to Java and don't know how the handle this kind of nested Maps.
I mean, asking for being pampered is a bit embarrassing, but maybe someone can show me how to do this in a correct way.
Edit: here how I add values, I haven't pasted this part of the code as I don't know HOW to check and decide what to do.
HashMap<String, HashMap<String, HashMap<String, String>>> vehiclesData = new HashMap<String, HashMap<String, HashMap<String, String>>>();
for( VehicleReportRow vehicleReportRow : unpreparedRows ){
String vehicle = vehicleReportRow.getVehicle();
String name = vehicleReportRow.getName();
String property = vehicleReportRow.getProperty();
String value = vehicleReportRow.getValue();
//the most inner dataset
HashMap<String,String> propAndVal = new HashMap<String, String>();
propAndVal.put(property, value);
//the middle dataset
HashMap<String, HashMap<String,String>> nameToProps = new HashMap<String, HashMap<String,String>>();
nameToProps.put(name, propAndVal);
//and finally the outer dataset
vehiclesData.put(vehicle, nameToProps);
}