2013-06-12 10:07:34 -07:00
|
|
|
/* This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
|
|
|
|
|
|
|
package org.mozilla.gecko.util;
|
|
|
|
|
2014-06-19 00:04:00 -07:00
|
|
|
import org.json.JSONArray;
|
2013-06-12 10:07:34 -07:00
|
|
|
import org.json.JSONException;
|
|
|
|
import org.json.JSONObject;
|
|
|
|
|
2014-04-25 07:28:00 -07:00
|
|
|
import android.os.Bundle;
|
|
|
|
import android.util.Log;
|
|
|
|
|
2014-06-19 00:04:00 -07:00
|
|
|
import java.util.HashSet;
|
|
|
|
import java.util.Set;
|
2014-04-25 07:28:00 -07:00
|
|
|
import java.util.UUID;
|
|
|
|
|
2013-06-12 10:07:34 -07:00
|
|
|
public final class JSONUtils {
|
2014-04-25 07:28:00 -07:00
|
|
|
private static final String LOGTAG = "GeckoJSONUtils";
|
|
|
|
|
2013-06-12 10:07:34 -07:00
|
|
|
private JSONUtils() {}
|
|
|
|
|
|
|
|
public static UUID getUUID(String name, JSONObject json) {
|
|
|
|
String uuid = json.optString(name, null);
|
|
|
|
return (uuid != null) ? UUID.fromString(uuid) : null;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void putUUID(String name, UUID uuid, JSONObject json) {
|
|
|
|
String uuidString = uuid.toString();
|
|
|
|
try {
|
|
|
|
json.put(name, uuidString);
|
|
|
|
} catch (JSONException e) {
|
|
|
|
throw new IllegalArgumentException(name + "=" + uuidString, e);
|
|
|
|
}
|
|
|
|
}
|
2014-04-25 07:28:00 -07:00
|
|
|
|
|
|
|
public static JSONObject bundleToJSON(Bundle bundle) {
|
|
|
|
if (bundle == null || bundle.isEmpty()) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
JSONObject json = new JSONObject();
|
|
|
|
for (String key : bundle.keySet()) {
|
|
|
|
try {
|
|
|
|
json.put(key, bundle.get(key));
|
|
|
|
} catch (JSONException e) {
|
|
|
|
Log.w(LOGTAG, "Error building JSON response.", e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return json;
|
|
|
|
}
|
2014-06-19 00:04:00 -07:00
|
|
|
|
|
|
|
// Handles conversions between a JSONArray and a Set<String>
|
|
|
|
public static Set<String> parseStringSet(JSONArray json) {
|
|
|
|
final Set<String> ret = new HashSet<String>();
|
|
|
|
|
|
|
|
for (int i = 0; i < json.length(); i++) {
|
|
|
|
try {
|
|
|
|
ret.add(json.getString(i));
|
|
|
|
} catch(JSONException ex) {
|
|
|
|
Log.i(LOGTAG, "Error parsing json", ex);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
|
2013-06-12 10:07:34 -07:00
|
|
|
}
|