I want to convert dot notated string to a JSONObject but include arrays too, for example: I want to set first.second[0].third[0].fourth to some string. So, JSON must be:
{
  "first": {
    "second": [
      {
        "third": [
          "fourth": "some string"
        ]
      }
    ]
  }
}
I found this method then edited and it turned out something like this:
private void expand(Object parent, String key, String value) {
    if (key == null) return;
    if (!key.contains(".") && !key.contains("[")) {
        if (parent instanceof JSONObject) {
            ((JSONObject) parent).put(key, value);
        } else {
            ((JSONArray) parent).put(value);
        }
        return;
    }
    String innerKey = key.substring(0, key.contains(".") ? key.indexOf(".") : key.length());
    String formattedInnerKey = innerKey.contains("[") ? innerKey.substring(0, innerKey.indexOf("[")) : innerKey;
    String remaining = key.contains(".") ? key.substring(key.indexOf(".") + 1) : key.contains("]") ? key.substring(key.indexOf("]") + 1) : null;
    if (parent instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) parent;
        if (jsonObject.has(formattedInnerKey)) {
            expand(jsonObject.get(formattedInnerKey), remaining, value);
            return;
        }
    } else {
        JSONArray jsonArray = (JSONArray) parent;
        Matcher matcher = Pattern.compile("(?<=\\[)([^\\]]+)(?=\\])").matcher(innerKey);
        Preconditions.checkState(matcher.find(), String.format("Matcher couldn't find a index number in \"%s\"", innerKey));
        int index = Integer.parseInt(matcher.group());
        System.out.print(index + " - ");
        if (!jsonArray.isNull(index)) {
            System.out.print(jsonArray.get(index));
            expand(jsonArray.get(index), remaining, value);
            return;
        }
    }
    Object obj = innerKey.contains("[") ? new JSONArray() : new JSONObject();
    if (parent instanceof JSONObject) {
        ((JSONObject) parent).put(formattedInnerKey, obj);
    } else {
        JSONObject base = new JSONObject();
        base.put(formattedInnerKey, obj);
        Matcher matcher = Pattern.compile("(?<=\\[)([^\\]]+)(?=\\])").matcher(innerKey);
        Preconditions.checkState(matcher.find(), String.format("Matcher couldn't find a index number in \"%s\"", innerKey));
        int index = Integer.parseInt(matcher.group());
        ((JSONArray) parent).put(index, base);
    }
    expand(obj, remaining, value);
}
This method -kinda- works but the problem is that it adds elements to the array instead of putting. I want to be able to put the object to an index in that array. How can I fix this?
