简体   繁体   中英

How do I send multiple Json data using HttpPost in android

[
   {
    "val1" : -1,
    "val2" : -1,
    "id" : 0,
    "diff" : -1,
    },
{
   ….
 }
]

I have a list of data that I need to send to the server. I am sending al the data via HttpPost I got the data in Json and created a string as follows but how do I send all the data and not just that one string together. On the server side it takes 50 such data list.

      JSONObject jsonObject = new JSONObject();
      ArrayList<String> mydata = new ArrayList<String> data();

      String json = "";
      jsonObject.accumulate("val1", val);
      jsonObject.accumulate("val2", val2);
      jsonObject.accumulate("id", id);
      jsonObject.accumulate("diff", diff);
      json = jsonObject.toString();
       mydata.add(json);

EDIT: On using JSONArray: {"Status":{"Code":699,"Description":"Cannot deserialize the current JSON array (eg [1,2,3]) into type 'System.Single' because the type requires a JSON primitive value (eg string, number, boolean, null) to deserialize correctly.\ \ To fix this error either change the JSON to a JSON primitive value (eg string, number, boolean, null) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\ \ Path '[0].Speed', line 1, position 11."}}

You need to use the JsonArray instance not appending the JsonObject result String to an ArrayList.

and the second fault is that you are using accumulate rather than put map the key to the value because the accumulate method appends the value to a JsonArray mapped to the key you provided.

JSONArray jsonArray = new JSONArray();
// for every item in the 50 item you need to send
JSONObject obj = new JSONObject();
jsonObject.put("val1", val);
jsonObject.put("val2", val2);
jsonObject.put("id", id);
jsonObject.put("diff", diff);
jsonArray.put(obj);
// then you need to send the data to the server
String data = jsonArray.toString();

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