0

i have three array list and i need to send it from servlet to android device....I have searched the similar problem here but i could not understand how do i retrieve all three Array List seperately. Here is servlet code:

.....
ArrayList<String> List1 = new ArrayList<String>();
ArrayList<String> List2 = new ArrayList<String>();
ArrayList<String> List3 = new ArrayList<String>();
public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
list1.add("item1.1");
list1.add("item1.2");
list1.add("item1.3");


list2.add("item2.1");
list2.add("item2.2");
list2.add("item2.3");

list3.add("item3.1");
list3.add("item3.2");
list3.add("item3.3");

String json1 = new Gson().toJson(list1);
String json2 = new Gson().toJson(list2);
String json3 = new Gson().toJson(list3);

res.setContentType("application/json");
res.setCharacterEncoding("UTF-8");

res.getWriter().write(json1);
res.getWriter().write(json2);
res.getWriter().write(json3);
 }

Now please help me to show android side coding....or give some hint or link. Thanks.

1 Answer 1

1

Rather than converting each List into JSON, create a Map of key as string and value as list of items as follow:

Map<String, ArrayList<String>> listMap = new HashMap<String, ArrayList<String>>();
listMap.put("json1", list1);
listMap.put("json2", list2);
listMap.put("json3", list3);

String finalJSON = new Gson().toJson(listMap);

The resulting JSON will be :

{
    "json1": [
        "item1.1",
        "item1.2",
        "item1.3"
    ],
    "json2": [
        "item2.1",
        "item2.2",
        "item2.3"
    ],
    "json3": [
        "item3.1",
        "item3.2",
        "item3.3"
    ]
}

Now on Android side, create POJO representing your servlet's json string response. And using gson parse the JSON string into the POJO.

EDIT :: On Android side use :

Map<String, ArrayList<String>> map = new Gson().fromJson(finalJSON, Map.class);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help....this is good way. But i am first time using JSON can you please help me how to parse JSON back to three ArrayList as they were in servlet. Or any link please.!!!
@aseem - You are welcome. And I am just another programmer like you..not "sir"...Also If the answer works for you than you can mark it as accept

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.