Skip to content Skip to sidebar Skip to footer

Create This String Exactly In Android

I want to build 2 same products for Android and iOs. The iOs already works, but the android doesnt, that's because of the format of the string. in iOs this is: NSString*jsonString

Solution 1:

Create same string as you are getting in IOS by create an JosnObject as:

JSONObject json = newJSONObject(); 
json.put("id", "0612833398"); 
json.put("longitude", "-143.406417"); 
json.put("latitude", "32.785834"); 
json.put("timestamp", "10-10 07:56"); 

now if you make a print for json object you will get this string :

{"id":"0612833398","longitude":"-143.406417","latitude":"32.785834","timestamp":"10-10 07:56"}

and Post JSONObject as to server :

try {
        HttpClienthttpclient=newDefaultHttpClient();

        HttpPosthttppost=newHttpPost("http://www.myserver.nl/locatie.php");
        httppost.setHeader("Content-type", "application/json");

// Create json object here...JSONObjectjson=newJSONObject(); 
    json.put("id", "0612833398"); 
    json.put("longitude", "-143.406417"); 
    json.put("latitude", "32.785834"); 
    json.put("timestamp", "10-10 07:56"); 

/// create StringEntity with current json obejctStringEntityse=newStringEntity(json.toString()); 
    se.setContentEncoding(newBasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    httppost.setEntity(se); 

        HttpResponseresponse= httpclient.execute(httppost);
        Stringtemp= EntityUtils.toString(response.getEntity());

    } catch (ClientProtocolException e) {

  } 

Solution 2:

To create a String you can use String.format(). In this case the syntax is very similar to Objective-C:

String s =String.format("{\"id\":\"%s\",\"longitude\":\"%s\",\"latitude\":\"%s\",\"timestamp\":\"%s\"}", num, long, lat, time);

HTTP Post goes like this:

HttpPost postMethod = new HttpPost(url);


try {

HttpParams params = new BasicHttpParams();

params.setParameter(name, value);


postMethod.setParams(params);

httpClient.execute(postMethod);


} catch (Exception e) {

} finally {

postMethod.abort();

}

Post a Comment for "Create This String Exactly In Android"