Nambi
Nambi

Reputation: 12042

How to post nested JSON data in Android?

I need to post the below JSON data from Android to a Webservice. This is JSON data

{"AutoMobileName":"Mercedes","Engine":"V4","BrandInfo":{"Model":"C500","ColorType" : "Black","DatePurchased":"1990"}}

Using Android Java i am doing like this.

JSONObject holder = new JSONObject();
holder.put("AutoMobileName", "Mercedes");
holder.put("Engine", "V4");
StringEntity se = new StringEntity(holder.toString());
httpost.setEntity(se);

Using the above code, the two parameters gets posted , but how do i send the BrandInfo data as it nested.

How do i put it inside the holder object and post it ?

Upvotes: 1

Views: 1725

Answers (3)

navneet sharma
navneet sharma

Reputation: 680

    JSONObject holder = new JSONObject();
    JSONObject innerholder = new JSONObject();
    innerholder .put("Model", "C500");
    innerholder .put("ColorType", "Black");
    innerholder .put("DatePurchased", "1990");

    holder.put("BrandInfo", innerholder);
    holder.put("AutoMobileName", "Mercedes");
    holder.put("Engine", "V4");


StringEntity se = new StringEntity(holder.toString());
httpost.setEntity(se);

Upvotes: 1

Jhanvi
Jhanvi

Reputation: 5139

Do it like this:

     JSONObject holder = new JSONObject();

    //BrandInfo
    JSONObject brandInfo = new JSONObject();
    brandInfo.put("Model", "C500");
    brandInfo.put("ColorType", "Black");
    brandInfo.put("DatePurchased", "1990");


    holder.put("AutoMobileName", "Mercedes");
    holder.put("Engine", "V4");
    holder.put("BrandInfo", brandInfo);
    System.out.println(holder);

Upvotes: 7

Mitaksh Gupta
Mitaksh Gupta

Reputation: 1029

Create another json object for brand info

JSONObject brandInfo = new JSONObject();
brandInfo.put("Model","C500");
brandInfo.put("ColorType","Black");
brandInfo.put("DatePurchased","1990");

and assign it to the holder variable as follows :

JSONObject holder = new JSONObject();
holder.put("AutoMobileName", "Mercedes");
holder.put("Engine", "V4");
holder.put("BrandInfo", brandInfo);
StringEntity se = new StringEntity(holder.toString());
httpost.setEntity(se);

Upvotes: 1

Related Questions