JSONUtil.java 2.04 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  org.apache.jackrabbit.util.ISO8601
 *  org.json.JSONArray
 *  org.json.JSONException
 *  org.json.JSONObject
 */
package com.adobe.granite.rest.impl.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.jackrabbit.util.ISO8601;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public final class JSONUtil {
    private JSONUtil() {
    }

    public static Map<String, Object> toJcrMap(JSONObject json) throws JSONException, IOException {
        HashMap<String, Object> map = new HashMap<String, Object>();
        JSONUtil.walk(map, json, null);
        return map;
    }

    private static void walk(Map<String, Object> properties, JSONObject json, String name) throws JSONException, IOException {
        String[] arrstring = JSONObject.getNames((JSONObject)json);
        int n = arrstring.length;
        for (int i = 0; i < n; ++i) {
            Object value;
            String key;
            String path = key = arrstring[i];
            if (name != null) {
                path = name + "/" + key;
            }
            if ((value = json.get(key)) instanceof JSONObject) {
                JSONUtil.walk(properties, (JSONObject)value, path);
                continue;
            }
            properties.put(path, JSONUtil.convert(value));
        }
    }

    private static Object convert(Object value) {
        if (value instanceof JSONArray) {
            JSONArray array = (JSONArray)value;
            ArrayList<Object> list = new ArrayList<Object>();
            for (int i = 0; i < array.length(); ++i) {
                Object o = array.opt(i);
                if (o == null) continue;
                list.add(o);
            }
            return list.toArray();
        }
        if (value instanceof String && ((String)value).matches("^\\d{4}-\\d{2}-\\d{2}.*$")) {
            return ISO8601.parse((String)((String)value));
        }
        return value;
    }
}