-1

i need to create JSON and set array list on a field. We have api of C#,.NET and they want me to send a JSON.

They want these parameters to be used:

"CustomerID": 1, "AddressID": 1, "Array": arraylist

how can i do that ?

Hems
  • 1
  • 8
  • check it once http://stackoverflow.com/questions/17810044/android-create-json-array-and-json-object – Ranjit May 21 '15 at 07:36

2 Answers2

1

You can use Google's Json library called Gson for serialization and deserialization.

I am assuming you are using Android Studio, if not you can still import this library to your project. First, add this line to your module's build.gradle file's dependencies:

compile 'com.google.code.gson:gson:2.3.1'

Then create a class, add your variables and tag them for JSON:

public class ToJson {

    @SerializedName("CustomerID")
    public int CustomerId;

    @SerializedName("AddressID")
    public int AddressId;

    @SerializedName("Array")
    public List array;
}

Create an object and populate:

ToJson toJson = new ToJson();
toJson.CustomerId = 1;
toJson.AddressId = 1;
toJson.array = new ArrayList<>();
toJson.array.add("Item 1");
toJson.array.add("Item 2");
toJson.array.add("Item 3");

Then create a Gson object and use it for serialization:

Gson gson = new Gson();
String JSON = gson.toJson(toJson);

The output JSON string is:

{
  "Array": [
    "Item 1",
    "Item 2",
    "Item 3"
  ],
  "CustomerID": 1,
  "AddressID": 1
}

This is simple as that. You can also check Gson User Guide for further information about serialization/deserialization.

Mustafa Berkay Mutlu
  • 1,929
  • 1
  • 25
  • 37
0

I can recommend using Jackson.

You only need to implement a POJO and annotate it.

Check this out. http://www.studytrails.com/java/json/java-jackson-Serialization-list.jsp

Flaxie
  • 540
  • 3
  • 13