13

I need to pass some parameters to server that i need to pass as below format

{
  "k2": {
    "mk1": "mv1",
    "mk2": [
      "lv1",
      "lv2"
    ]
  }
}

So how can generate this format in android.

I tried this using the As shown in example 5.3 but it is showing a error at obj.writeJSONString(out); this line. Can anyone please help in solving this.

Thanks In Advance

4 Answers 4

39

Its not that though at all, output you want is JSONArray inside JSONObject and JSONObject inside another JSONObject. So, you can create them seperately and then can put in together. as below.

try {
            JSONObject parent = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            jsonArray.put("lv1");
            jsonArray.put("lv2");

            jsonObject.put("mk1", "mv1");
            jsonObject.put("mk2", jsonArray);
            parent.put("k2", jsonObject);
            Log.d("output", parent.toString(2));
        } catch (JSONException e) {
            e.printStackTrace();
        }

Output-

       {
           "k2": {
             "mk1": "mv1",
             "mk2": [
               "lv1",
               "lv2"
             ]
           }
         }
Sign up to request clarification or add additional context in comments.

3 Comments

+1 I am new to JSON parsing . This clear example was all that i needed :-)
@LalitPoptani What is the 2 in Log.d("output", parent.toString(2));? Is it spacing?
@CompaqLE2202x Yes, it is the spacing & formatting in the output of Json.
6

You can use JSONObject and construct your data with it.

Here is the Documentation link

jsonObject.toString() // Produces json formatted object

2 Comments

Can you post the exception details ?
Are you importing org.json.JSONObject ?
2

Hi first you have to create separate class HttpUtil.java.See following the code

public class HttpUtil {

// lat=50.2911 lon=8.9842

private final static String TAG = "DealApplication:HttpUtil";

public static String get(String url) throws ClientProtocolException,
        IOException {
    Log.d(TAG, "HTTP POST " + url);
    HttpGet post = new HttpGet(url); 
    HttpResponse response = executeMethod(post);
    return getResponseAsString(response);
}

public static String post(String url, HashMap<String, String> httpParameters)
        throws ClientProtocolException, IOException {
    Log.d(TAG, "HTTP POST " + url);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
            httpParameters.size());
    Set<String> httpParameterKeys = httpParameters.keySet();
    for (String httpParameterKey : httpParameterKeys) {
        nameValuePairs.add(new BasicNameValuePair(httpParameterKey,
                httpParameters.get(httpParameterKey)));
    }

    HttpPost method = new HttpPost(url);
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs);
    System.out.println("**************Request=>"+urlEncodedFormEntity.toString());
    method.setEntity(urlEncodedFormEntity);
    HttpResponse response = executeMethod(method);

    return getResponseAsString(response);
}

private static HttpResponse executeMethod(HttpRequestBase method)
        throws ClientProtocolException, IOException {
    HttpResponse response = null;
    HttpClient client = new DefaultHttpClient();
    response = client.execute(method);
    Log.d(TAG, "executeMethod=" + response.getStatusLine());
    return response;
}

private static String getResponseAsString(HttpResponse response)
        throws IllegalStateException, IOException {
    String content = null;
    InputStream stream = null;
    try {
        if (response != null) {
            stream = response.getEntity().getContent();
            InputStreamReader reader = new InputStreamReader(stream);
            BufferedReader buffer = new BufferedReader(reader);
            StringBuilder sb = new StringBuilder();
            String cur;
            while ((cur = buffer.readLine()) != null) {
                sb.append(cur + "\n");
            }
            content = sb.toString();
            System.out.println("**************Response =>"+content);
        }
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
    return content;
}

}

Comments

0

This example is help you just call this function it will return JSON as string value.. Try it

 public String getResult() {
    JSONObject userResults = null;
    try {
        userResults = new JSONObject();
        userResults.put("valueOne",str_one);
        userResults.put("valueTwo", str_two);
        userResults.put("valueThree" ,str_three);
        userResults.put("valueFour", str_four);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return userResults.toString();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.