diff --git a/mobile/android/base/Makefile.in b/mobile/android/base/Makefile.in index 4ddbc430d0e..70816d829ec 100644 --- a/mobile/android/base/Makefile.in +++ b/mobile/android/base/Makefile.in @@ -38,6 +38,7 @@ UTIL_JAVA_FILES := \ util/HardwareUtils.java \ util/INIParser.java \ util/INISection.java \ + util/JSONUtils.java \ util/StringUtils.java \ util/ThreadUtils.java \ util/UiAsyncTask.java \ diff --git a/mobile/android/base/util/JSONUtils.java b/mobile/android/base/util/JSONUtils.java new file mode 100644 index 00000000000..b883d7f979c --- /dev/null +++ b/mobile/android/base/util/JSONUtils.java @@ -0,0 +1,57 @@ +/* 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; + +import org.json.JSONException; +import org.json.JSONObject; + +import android.util.Log; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.UUID; + +public final class JSONUtils { + private static final String LOGTAG = "JSONUtils"; + + private JSONUtils() {} + + public static URL getURL(String name, JSONObject json) { + String url = json.optString(name, null); + if (url == null) { + return null; + } + + try { + return new URL(url); + } catch (MalformedURLException e) { + Log.e(LOGTAG, "", new IllegalStateException(name + "=" + url, e)); + return null; + } + } + + public static void putURL(String name, URL url, JSONObject json) { + String urlString = url.toString(); + try { + json.put(name, urlString); + } catch (JSONException e) { + throw new IllegalArgumentException(name + "=" + urlString, e); + } + } + + 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); + } + } +}