I have a problem with json. I want my Json to look like:
data={"phoneId":1,"token":"APA91bF2tN5g1TtULFE5tysRMAarygjX4w9hjTGCqT3SL-PwiMV6aqTtkV3lpqLkc7msVfEdTnyd_pJVFNMM_fjEbeVSuCjiNPVKx7p9sYC1DoWnuKUurt31E1yh2RDwl_oprfKxEF18PP6Q8dXHZe6FeflE3CIxBg","appId":5}
This is my post to web service:
JSONObject jsonObject = new JSONObject();
jsonObject.put("token", regId);
jsonObject.put("appId", GlobalConfig.getAPPLICATION_ID());
jsonObject.put("phoneId", 1);
JSONArray jArrayParam = new JSONArray();
jArrayParam.put(jsonObject);
JSONObject finaljsonobj = new JSONObject();
finaljsonobj.put("data", jArrayParam);
System.out.println(jsonObject.toString());
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Token",jArrayParam.toString()));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(GlobalConfig.getSendEmail());
httppost.addHeader("Authorization", "Basic " + Base64.encodeToString(
(GlobalConfig.getAuthString()).getBytes(),Base64.NO_WRAP));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
How can I check if my json looks like one in my example? I want to check how my json is post to webservice.
try as:
JSONObject jsonObject = new JSONObject();
jsonObject.put("token", regId);
jsonObject.put("appId", GlobalConfig.getAPPLICATION_ID());
jsonObject.put("phoneId", 1);
System.out.println("data="+jsonObject.toString());
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Token","data="+jsonObject.toString()));
this will create your JSON object as:
data={
"phoneId": 1,
"token": "token",
"appId": 5
}
U can create wrapper class for your JSONObject:
public class YourWrapperClassName{
@SerializedName("phoneId")
private int phoneId;
@SerializedName("token")
private String token;
@SerializedName("appId")
private int appId;
}
Prepare your JSON object and view in debug how it looks:
YourWrapperClassName testObj = new YourWrapperClassName();
// initialize testObj fields
Gson gson = new Gson(); // import com.google.gson.Gson;
String result = gson.toJson(testObj); // put breakpoint here
Link for downloading Gson library - http://code.google.com/p/google-gson/downloads/list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With