I am creating an application that deals with cars and orders.
A order contains a car and other information (BUYER, OWNER, ...), which constructs an orderObject
.
A car has around 80 different attributes (TYP_WHEEL, TYP_DOOR, QUANTITY_WHEELS, ...) for the different car-parts.
I get the car-attributes and their values from a JSON string and put them into a map named allCarAttributes
.
The JSON has this structure:
result:
data[]:
characteristics_0[]: …
…
characteristics_1[]: …
…
…
…
characteristics_N[]: …
Each characteristics-array contains some attributes:
"result": {
"data": [
{
"characteristics": [
{
"description": "Car ceiling color",
"id": "COL_CAR_CEILING",
"value": "F8",
"valueDescription": "F8 - White"
},
{
"description": "Color Car Finishes",
"id": "COL_CAR_ACCESSORIES",
"value": "T",
"valueDescription": "ST- Stainless Steel"
},
{
"description": "Car flooring color",
"id": "COL_CAR_FLOORING",
"value": "RD10",
"valueDescription": "RD10, grey"
},
(...)
Then I go through this map and based on the attribute name I set the respective value in the orderObject
.
My problem:
Since the methods to set the values in the orderObject
each have different names, I am not able to find a more efficient way than using a switch-case
with 80 cases.
for (Map.Entry<String, String> attribute : allCarAttributes.entrySet()) {
switch (attribute.getKey()) {
case "TYP_DOOR":
orderObject.setDoor(attribute.getValue());
break;
case "TYP_WHEEL":
orderObject.setWheelType(attribute.getValue());
break;
case "QANTITY_WHEELS":
orderObject.setWheelNumber(attribute.getValue());
break;
(...)
default:
break;
}
}
The orderObject
-class simply has several fields and setters/getters for them:
private String car_width;
private String car_depth;
private String car_height;
private String car_weight;
(...)
public String getCar_width() {
return car_width;
}
public void setCar_width(String car_width) {
this.car_width = car_width;
}
How can I get rid of this huge switch-case
?
Should I get rid of it at all? The switch-case
works fine as it is, it is just very long and ugly.
car_width
for example is not a String but a number (maybeint
), safe for quantities. Can you post what your JSON looks like? Parsing it into an Object up-front using Gson or other JSON libraries will be a lot simpler. \$\endgroup\$orderObject
does not only contain information about the car-parts but several other outside I did not see how I could directly create anorderObject
via Gson. Therefore I create it "step-by-step" from the JSON + the other information. \$\endgroup\$