Blaze Tama
Blaze Tama

Reputation: 10948

How to send array as POST parameter/payload to webservice in Android using REST

Im using REST in my webservice. This is the example payload/parameter i sent when i test my webservice using advance rest client, with form content type (this is the RAW type):

child_id%5B%5D=1&user_id=15&group_id=1&custom=&time=17%3A17%3A00&date=&child_id%5B%5D=2

Where child_id%5B%5D in RAW means child_id[] in the form, so i send an array of child_id (left most and right most in above form). Things are fine here.

The problem occured when i tried to implement this to the Android apps, where i POST those payload/parameter using a HashMap. HashMap cant store two values under the same key, so i cant do something like :

map.put("child_id[]", 1);
map.put("child_id[]", 2);

The latest put will overwrite the earlier put, so the Android apps will only send 2 as value of the child_id.

What should i do? Thanks for your help

Upvotes: 0

Views: 1521

Answers (2)

Justin
Justin

Reputation: 2031

You have a few options for solving this. The easiest would be to create a class to act as a container for your parameters, and store those in an ArrayList

public class Parameter {
    private String key;
    private String value;
    // Getters, setters, other stuff.
}

Which you would then store in an ArrayList

You could also make a class to act as a parameter builder of sorts. You might do something like this:

public class Parameters {
    private ArrayList<String> keys = new ArrayList<>();
    private ArrayList<String> values = new ArrayList<>();

    public void add(String key, String value) { ... }
    public ArrayList<String> getKeys() { ... }
    public ArrayList<String> getValues() { ... }
}

The second option requires a bit more code but adds some extra flexibility and should make for a cleaner API.

Alternatively, as you mentioned in your own comment, you have the option of using a Map<String, ArrayList<String>>. Which would also work very well in place of the ArrayLists in the above example.

Upvotes: 1

Muthu
Muthu

Reputation: 1022

You Could add index to the array as follows.

map.put("child_id[0]", 1);
map.put("child_id[1]", 2);

Upvotes: 2

Related Questions