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

com.moengage.util.JSONUtil Maven / Gradle / Ivy

There is a newer version: 1.3.7
Show newest version
package com.moengage.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;

public class JSONUtil {

  public static List jsonArrayToList(JSONArray value) {
    List results = new ArrayList<>(value.length());
    for (int itemIndex = 0; itemIndex < ((JSONArray) value).length(); itemIndex++) {
      Object item = value.opt(itemIndex);
      if (item == null || JSONObject.NULL.equals(item)) {
        results.add(null);
      } else if (item instanceof JSONArray) {
        results.add(jsonArrayToList((JSONArray) item));
      } else if (item instanceof JSONObject) {
        results.add(jsonObjectToMap((JSONObject) item));
      } else {
        results.add(item);
      }
    }
    return results;
  }

  public static Map jsonObjectToMap(JSONObject value) {
    Map result = new HashMap<>();
    Iterator entryKeys = value.keys();
    while (entryKeys.hasNext()) {
      String itemKey = entryKeys.next();
      Object itemValue = value.opt(itemKey);
      if (itemValue == null || JSONObject.NULL.equals(itemValue)) {
        result.put(itemKey, null);
      } else if (itemValue instanceof JSONObject) {
        result.put(itemKey, jsonObjectToMap((JSONObject) itemValue));
      } else if (itemValue instanceof JSONArray) {
        result.put(itemKey, jsonArrayToList((JSONArray) itemValue));
      } else {
        result.put(itemKey, itemValue);
      }
    }
    return result;
  }
}