Last active
October 21, 2015 21:24
-
-
Save viperwarp/976298d553321430e34e to your computer and use it in GitHub Desktop.
Java JSON hashing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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