Monday, March 31, 2014

Create Json string Format to POST Json data to the Service-- With Array

 http://www.javacodegeeks.com/2013/10/android-json-tutorial-create-and-parse-json-data.html


public class JsonUtil {

public static String toJSon(Person person) {
      try {
        // Here we convert Java Object to JSON 
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("name", person.getName()); // Set the first name/pair 
        jsonObj.put("surname", person.getSurname());

        JSONObject jsonAdd = new JSONObject(); // we need another object to store the address
        jsonAdd.put("address", person.getAddress().getAddress());
        jsonAdd.put("city", person.getAddress().getCity());
        jsonAdd.put("state", person.getAddress().getState());

        // We add the object to the main object
        jsonObj.put("address", jsonAdd);

        // and finally we add the phone number
        // In this case we need a json array to hold the java list
        JSONArray jsonArr = new JSONArray();

        for (PhoneNumber pn : person.getPhoneList() ) {
            JSONObject pnObj = new JSONObject();
            pnObj.put("num", pn.getNumber());
            pnObj.put("type", pn.getType());
            jsonArr.put(pnObj);
        }

        jsonObj.put("phoneNumber", jsonArr);

        return jsonObj.toString();

    }
    catch(JSONException ex) {
        ex.printStackTrace();
    }

    return null;

}
 
 
{
   "phoneNumber": [
      {
         "type": "work",
         "num": "11111"
      },
      {
         "type": "home",
         "num": "2222"
      }
   ],
   "address": {
      "state": "World",
      "address": "infinite space, 000",
      "city": "Android city"
   },
   "surname": "Swa",
   "name": "Android"
}
========================================================