Note that there are some explanatory texts on larger screens.

plurals
  1. POMapping between JSON formats in Java
    primarykey
    data
    text
    <p>I'm coming to Java from JavaScript/Ruby. Let's say I've got the following JSON object for an animal:</p> <pre><code>{ name: { common: "Tiger", latin: "Panthera tigris" } legs: 4 } </code></pre> <p>I'm dealing with lots of animal APIs, and I want to normalize them all into my own common format, like:</p> <pre><code>{ common_name: "Tiger", latin_name: "Panthera tigris", limbs: { legs: 4, arms: 0 } } </code></pre> <p>In, say, JavaScript, this would be straightforward:</p> <pre><code>normalizeAnimal = function(original){ return { common_name: original.name.common, latin_name: original.name.latin, limbs: { legs: original.legs || 0, arms: original.arms || 0 } } } </code></pre> <p>But what about in Java? Using the JSONObject class from org.json, I could go down the road of doing something like this:</p> <pre><code>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; } </code></pre> <p>This gets worse as the JSON objects I'm dealing with get longer and deeper. In addition to all of this, I'm dealing with many providers for animal objects and I'll eventually be looking to have some succinct configuration format for describing the transformations (like, maybe, <code>"common_name": "name.common", "limbs.legs": "legs"</code>).</p> <p>How would I go about making this suck less in Java?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload