All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.backendless.utils.JSONObjectConverter Maven / Gradle / Ivy

There is a newer version: 7.0-alpha
Show newest version
package com.backendless.utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * When using easyLogin (for Facebook, Google+ or Twitter) the returned BackendlessUser can contain not correct fields:
 * JSONObject.NULL instead of null
 * JSONArray instead of List
 * JSONObject instead of Map
 *
 * This class is used to convert JSONObject.. fields into simple java.lang types
 */

public class JSONObjectConverter {
    public static Map toMap(JSONObject object) throws JSONException {
        Map map = new HashMap();
        Iterator keys = object.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            map.put(key, fromJson(object.get(key)));
        }
        return map;
    }

    public static List toList(JSONArray array) throws JSONException {
        List list = new ArrayList();
        for (int i = 0; i < array.length(); i++) {
            list.add(fromJson(array.get(i)));
        }
        return list;
    }

    public static Object fromJson(Object json) throws JSONException {
        if (json == JSONObject.NULL) {
            return null;
        } else if (json instanceof JSONObject) {
            return toMap((JSONObject) json);
        } else if (json instanceof JSONArray) {
            return toList((JSONArray) json);
        } else {
            return json;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy