1

I am trying to send this json to web server:

[{"codemenu":"1","name":"Fried Rice"},
{"codemenu":"2","name":"Hongkong Fried Rice"},
{"codemenu":"3","name":"Special fried Rice"}]

This is the code but it's not working:

HttpPost httppost = new HttpPost("http://10.0.2.2/pnir_restoran/test.php");
JSONObject json = new JSONObject();
try {
    // JSON data:
    json.put("codemenu", "1");
    json.put("name", "friedrice");
    json.put("codemenu", "2");
    json.put("name", "Hongkong friedrice");
    json.put("codemenu", "3");
    json.put("name", "Special friedrice");          

    JSONArray postjson=new JSONArray();
    postjson.put(json); //i cant use postjson.add(json);

    // Post the data:
    httppost.setHeader("json",json.toString());
    httppost.getParams().setParameter("jsonpost",postjson);

    // Execute HTTP Post Request
    System.out.print(json);
    HttpResponse response = httpclient.execute(httppost);

What should I do? Please help me.

4
  • Have you displayed the JSON that's being generated? What you're generating is not what you say you want. Commented Jun 6, 2012 at 3:09
  • (You're creating one JSON object and putting 6 entries in it. The JSON prototype you list contains 3 objects, each with 2 entries.) Commented Jun 6, 2012 at 3:10
  • (It also doesn't make sense that you're putting the JSON object in the header and the array in the params.) Commented Jun 6, 2012 at 3:12
  • yes that json that i want read in php @HotLicks Commented Jun 6, 2012 at 4:10

2 Answers 2

1

You need to use a JSONArray and then put individual JSONObjects inside the array:

// Initialize the JSON Array and your three seperate objects.
JSONArray jsonArray = new JSONArray();
JSONObject jObj1 = new JSONObject();
JSONObject jObj2 = new JSONObject();
JSONObject jObj3 = new JSONObject();

// Put elements in one object at a time and put them in your array.
jObj1.put("codemenu", "1");
jObj1.put("name", "friedrice");

jsonArray.put(jObj1);

jObj2.put("codemenu", "2");
jObj2.put("name", "Hongkong friedrice");

jsonArray.put(jObj2);

jObj3.put("codemenu", "3");
jObj3.put("name", "Special friedrice");

jsonArray.put(jObj3);
Sign up to request clarification or add additional context in comments.

2 Comments

but thats is static what should i do if the data is 100 i cant make the array of json object , @Tushar Dhoot
@stefan Use a loop with the code that needs to be repeated inside.
0

Instead of doing all JSON handling manually, you can use Spring Android's RestTemplate module.

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.