5

How to wrap given json to string and send it to server via Http put request in android?

This is how my json look like.

    {
    "version": "1.0.0",
    "datastreams": [
        {
            "id": "example",
            "current_value": "333"
        },
        {
            "id": "key",
            "current_value": "value"
        },
        {
            "id": "datastream",
            "current_value": "1337"
        }
    ]
}

above is my json array.

below is how I wrote the code but, its not working

        protected String doInBackground(Void... params) {
            String text = null;
            try {
                JSONObject child1 = new JSONObject();
                try{
                    child1.put("id", "LED");
                    child1.put("current_value", "0");


                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


                JSONArray jsonArray = new JSONArray();

                jsonArray.put(child1);

                JSONObject datastreams = new JSONObject();
                datastreams.put("datastreams", jsonArray);  

                JSONObject version = new JSONObject();
                version.put("version", "1.0.0");
                version.put("version", datastreams);


             HttpClient httpClient = new DefaultHttpClient();
             HttpContext localContext = new BasicHttpContext();
             HttpPut put = new HttpPut("url");
             put.addHeader("X-Apikey","");
             StringEntity se = new StringEntity( version.toString());  
             se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

             put.addHeader("Accept", "application/json");
             put.addHeader("Content-type", "application/json");
             put.setEntity(se);


             try{

                   HttpResponse response = httpClient.execute(put, localContext);
                   HttpEntity entity = response.getEntity();
                   text = getASCIIContentFromEntity(entity);
             }
              catch (Exception e) {
                 return e.getLocalizedMessage();
             }


        }catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
            return text;
        }

please help on this

Jimit
  • 73
  • 1
  • 2
  • 7
  • Use gson, it will help you wrap unwrap your jsons and objects – Hardik4560 Jan 27 '14 at 09:10
  • SO is not a `give me teh codez!!1` site. Please provide what you have tried so far. If you haven't done anything, please try at least google and **then** if you still can't manage - ask here – Mario Stoilov Jan 27 '14 at 09:10
  • in general, _to wrap given json to string_ is just to put it into quotes and escape the internal quotes. "{ \"version\": \"1.0.0\", \"datastreams\": [ { \"id\": \"example\", \"current_value\": \"333\" }, { \"id\": \"key\", \"current_value\": \"value\" }, { \"id\": \"datastream\", \"current_value\": \"1337\" } ] }" -- you need to open a text editor window and replace all "-s with \"-s – 18446744073709551615 Jan 27 '14 at 09:13
  • if u solved ur problem then check as a correct answer which solved.......! – Prasad Aug 26 '14 at 14:28

5 Answers5

4

this is one sample.

    JSONObject Parent = new JSONObject();
    JSONArray array = new JSONArray();

    for (int i = 0 ; i < datastreamList.size() ; i++)
    {
        JSONObject jsonObj = new JSONObject();

        jsonObj.put("id", datastreamList.get(i).GetId());
        jsonObj.put("current_value", datastreamList.get(i).GetCurrentValue());
        array.put(jsonObj);
    }       
    Parent.put("datastreams", array);       
    Parent.put("version", version);

and for sending that:

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    StringEntity se = new StringEntity( Parent.toString());  
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    post.setHeader("Accept", "application/json");
    post.setHeader("Content-type", "application/json");
    post.setEntity(se);
    client.execute(post);

EDIT

in this sample datastreamList that used in for statement is a list that you must have for all value that want send to server ( one list of one class that have 2 property , id and value ), actually i think you have two class like bellow:

class A {

List<Datastreams> datastreamList
String version;
//get
//set
}

class Datastreams {

String id;
String current_value; // or int
//get
//set
}

and in your code you must have one object of A class that want send to server, so you can use first part to map your object to json.

Shayan Pourvatan
  • 11,898
  • 4
  • 42
  • 63
  • But, how to write "current_value" for particular "id" ?? ex. "current_value" = "0" – Jimit Jan 27 '14 at 11:08
  • i don't get you, can you explain better? – Shayan Pourvatan Jan 27 '14 at 11:22
  • "current_value" is something where we can update data like 1,2,3 or with any char. So, how should I write actual data to above code? – Jimit Jan 27 '14 at 17:22
  • also, this code in eclipse shows "datastreams can not be resolved". What to do next? – Jimit Jan 27 '14 at 17:41
  • class A { List datastreamList String version= 1.0.0; } class datastreams { String id=example; int current_value=0; // or int } Is this class will work?? Because I am new to this. – Jimit Jan 28 '14 at 08:33
  • I was doing like this jsonObj.put("id", "LED"); jsonObj.put("current_value", "0"); but, it was not helping to send data. – Jimit Jan 28 '14 at 10:08
  • with this code you just have `datastreams` tag, what about `version`? can you edit your post with new code? – Shayan Pourvatan Jan 28 '14 at 10:20
  • I have wrote the code above in question, but its not working. Would you please give me full detail of working code? – Jimit Jan 28 '14 at 19:13
  • `its not working` not a good describe of your problem, above code is a complete, you just need put your set and get method in two class and before for statement put your list in `datastreamList`, rest of code do your job. – Shayan Pourvatan Jan 29 '14 at 04:51
  • Hello Shayan , I am not saying your code is not working. I have posted the code on which I was working in question is not giving any output. – Jimit Jan 29 '14 at 09:19
  • for checking your `json` you can use `log version.toString()` to make Sure your json is correct or not, but in first look you need put your version Json in another `jsonObject` and then send that. and change tag of `version.put("version", datastreams);` to `datastreams` – Shayan Pourvatan Jan 29 '14 at 09:34
2

If you prefer to use a library then I'll prefer you to use Ion Library by Kaush.

Form this library you can simply post your JSON like this :

JsonObject json = new JsonObject();
json.addProperty("foo", "bar");

Ion.with(context, "http://example.com/post")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
   @Override
    public void onCompleted(Exception e, JsonObject result) {
        // do stuff with the result or error
    }
});
Vipul Purohit
  • 9,807
  • 6
  • 53
  • 76
0

Just you have to send as a String so store following JSON data in String

{
    "version": "1.0.0",
    "datastreams": [
        {
            "id": "example",
            "current_value": "333"
        },
        {
            "id": "key",
            "current_value": "value"
        },
        {
            "id": "datastream",
            "current_value": "1337"
        }
    ]
}

then you have to send like:

pairs.add(new BasicNameValuePair("data", finalJsonObject.toString()));
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
0

The '{' bracket represent a object and '[' represent an array or list. In your case create a bean

YourObj{
private String version;
private List<DataStream> datastreams;
//getters
//setters 
}
DataStream{
private String id;
private String current_value;
//getters
//setters
}

use org.codehaus.jackson:jackson-xc jar for json parssing

use ObjectMapper

String to Object

 YourObj obj = new ObjectMapper().readValue(stringyouwanttopass,new TypeReference<YourObj>(){});

now you can use the parsed value.

or you can set the values to the YourObj

YourObj obj =new YourObj();
obj.setVersion(1.0.0);
List<Datastream> datastreams=new ArrayList<Datastream>();
Datastream datestr=new Datastream();
datestr.setId("example");
datestr.setCurrent_value("333");
datastreams.add(datestr);
datestr.setId("key");
datestr.setCurrent_value("value");
datastreams.add(datestr);
datestr.setId("datastream");
datestr.setCurrent_value("1337");
datastreams.add(datestr);
JSONObject jsonget = new JSONObject(appObject);
jsonget.toString();

Connecting server using Jersey

Client client = Client.create();
WebResource webResource = client.resource("serverURl");
ClientResponse response = webResource.path("somePath")
                    .type("application/json").accept("application/json")
                    .post(ClientResponse.class, jsonget.toString());

in the server side get it as string and parse it.

jos
  • 1,082
  • 5
  • 19
  • 45
0

here is a android Client library can help you: Httpzoid - Android REST (JSON) Client,it has some examples and you can do put post,get request easily. https://github.com/kodart/Httpzoid

Jack Li
  • 9
  • 2