Skip to content

Instantly share code, notes, and snippets.

@viperwarp
Last active October 21, 2015 21:24
Show Gist options
  • Save viperwarp/976298d553321430e34e to your computer and use it in GitHub Desktop.
Save viperwarp/976298d553321430e34e to your computer and use it in GitHub Desktop.
Java JSON hashing
private long getJsonHashcode(@NonNull Object json) throws JSONException {
long result = 15l;
int multiplier = 27;
if (json instanceof JSONObject) {
JSONObject obj = (JSONObject) json;
for (Iterator<String> iterator = obj.keys(); iterator.hasNext(); ) {
String key = iterator.next();
Object value = obj.get(key);
result = multiplier * result + key.hashCode();
if (value instanceof JSONArray || value instanceof JSONObject) {
result = multiplier * result + getJsonHashcode(value);;
} else {
result = multiplier * result + String.valueOf(value).hashCode();
}
}
} else if (json instanceof JSONArray) {
JSONArray array = (JSONArray) json;
for (int i = 0; i < array.length(); i++) {
Object value = array.get(0);
if (value instanceof JSONArray || value instanceof JSONObject) {
result = multiplier * result + getJsonHashcode(value);
} else {
result = multiplier * result + String.valueOf(value).hashCode();
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment