How to Parse JsonObject of JsonObjects in String and send over post request using urlconnection android?

201 views Asked by At

I have a web service in which I have to pass parameters in Json. But the problem is jsonObject have one key with jsonobject type and that jsonobject have one key with again son type. It is pretty confusing but I can show you my final result with son object.

{
    "Id": 1,
    "Company": "BMW",
    "Category": {
        "ID": 1,
        "Transmission": 1,
        "Fuel": 2,
        "Description": {
            "Price": 1200000,
            "Year": 2016
        }
    }
}

Now I want to send it in URLconnection. What should I do?

I create 3 Json objects with description,Category,and final son and then converted it to String with toString(). putted Description in Category and Category in final son with “Category” key But its not working server is giving error.

I am very new to android and don’t have much idea about it. Any suggestion will be useful.

Edited I already tried that link but still not solved my problem.

2

There are 2 answers

0
dsncode On

if you want to use URLConnection.. you might want to see this thread

POST request send json data java HttpUrlConnection

0
Wajid On

My first suggestion would be to use a library for http communication:

  1. Volley
  2. OkHttp
  3. Retrofit etc

They will handle json for you.

if you still want to use that httpUrlConnection:

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));

conn.connect();

This is how you can add value to it. Now you may add you json.toString() as a parameter and give a proper key to it which is identified by the server;