简体   繁体   中英

Parsing multiple Json Objects in android

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.

You need to use a JSONArray and then put individual JSONObject s 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);

您可以使用Spring Android的RestTemplate模块来代替手动进行所有JSON处理。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM