如何將給定的JSON包裝到字符串並通過Http把請求發送到服務器android?發送JSON到服務器通過HTTP放置請求在android
這就是我的json的樣子。
{
"version": "1.0.0",
"datastreams": [
{
"id": "example",
"current_value": "333"
},
{
"id": "key",
"current_value": "value"
},
{
"id": "datastream",
"current_value": "1337"
}
]
}
上面是我的json數組。
下面是我寫的代碼,但它不工作
protected String doInBackground(Void... params) {
String text = null;
try {
JSONObject child1 = new JSONObject();
try{
child1.put("id", "LED");
child1.put("current_value", "0");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(child1);
JSONObject datastreams = new JSONObject();
datastreams.put("datastreams", jsonArray);
JSONObject version = new JSONObject();
version.put("version", "1.0.0");
version.put("version", datastreams);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPut put = new HttpPut("url");
put.addHeader("X-Apikey","");
StringEntity se = new StringEntity(version.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
put.addHeader("Accept", "application/json");
put.addHeader("Content-type", "application/json");
put.setEntity(se);
try{
HttpResponse response = httpClient.execute(put, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
}
catch (Exception e) {
return e.getLocalizedMessage();
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return text;
}
請在此
使用gson,它將幫助你包裝解開你的jsons和對象 – Hardik4560
SO不是'給我teh codez !! 1'網站。請提供您迄今爲止所嘗試的內容。如果你沒有做任何事情,請至少嘗試谷歌和** **然後如果你仍然不能管理 - 在這裏問 –
一般,給JSON來string_ _TO包裝只是把它放到引號和逃避內部引號。 「{」\「version \」:\「1.0.0 \」, \「datastreams \」:[ \「id \」:\「example \」, \「current_value \」:\「333 \」 }, { \ 「ID \」:\ 「鍵\」, \ 「current_value \」:\ 「值\」 }, { \ 「ID \」:\ 「數據流\」, \「current_value \」:\「1337 \」 } ] }「 - 您需要打開一個文本編輯器窗口,並將所有的」-s替換爲\「 - s – 18446744073709551615