I come in Java with JavaScript / Ruby. Let's say I have the following JSON object for an animal:
{ name: { common: "Tiger", latin: "Panthera tigris" } legs: 4 }
I deal with a lot of animal APIs and I want to normalize them all to my own common format, for example:
{ common_name: "Tiger", latin_name: "Panthera tigris", limbs: { legs: 4, arms: 0 } }
In, say, JavaScript, this would be simple:
normalizeAnimal = function(original){ return { common_name: original.name.common, latin_name: original.name.latin, limbs: { legs: original.legs || 0, arms: original.arms || 0 } } }
But what about Java? Using the JSONObject class from org.json, I could go this way:
public JSONObject normalizeAnimal(JSONObject original) throws JSONException{ JSONObject name = original.getJSONObject("name"); JSONObject limbs = new JSONObject(); JSONObject normalized = new JSONObject(); normalized.put("name_name", name.get("common")); normalized.put("latin_name", name.get("latin")); try{ limbs.put("legs", original.get("legs"); }catch(e){ limbs.put("legs", 0); }; try{ limbs.put("arms", original.get("arms"); }catch(e){ limbs.put("arms", 0); }; normalized.put("limbs", limbs); return normalized; }
This gets worse as the JSON objects I'm dealing with are getting longer and deeper. In addition to all this, I deal with many providers for animal objects, and ultimately I want to have a compressed configuration format for describing the transformations (for example, perhaps "common_name": "name.common", "limbs.legs": "legs" ).
How can I make it suck less in Java?