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

com.chargebee.internal.CompositeArrayParameter Maven / Gradle / Ivy

There is a newer version: 3.26.0
Show newest version
package com.chargebee.internal;

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

import java.util.HashMap;
import java.util.Map;

public class CompositeArrayParameter extends CompositeParameter {
    Integer index;

    public CompositeArrayParameter(String name, String nestedParameterName, Integer index) {
        super(name, nestedParameterName);
        this.index = index;
    }

    @Override
    Map toFormURLEncoded(Map paramsMap) {
        return new HashMap() {{
            put(name + "[" + nestedParameterName + "][" + index + "]", value);
        }};
    }

    @Override
    JSONObject toJSONBody(JSONObject paramsJSON) {
        JSONArray existingArray = paramsJSON.opt(name) != null ? paramsJSON.optJSONArray(name) : new JSONArray();
        if (index > 0 && existingArray.opt(index - 1) == null) {
            throw new RuntimeException("Please add items to the array with ordered array indices");
        }
        JSONObject existingArrayItem = existingArray.optJSONObject(index) != null ? existingArray.optJSONObject(index) : new JSONObject();
        existingArrayItem.put(nestedParameterName, value);
        existingArray.put(index, existingArrayItem);
        paramsJSON.put(name, existingArray);
        return paramsJSON;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy