在寫在ASP .NET下基於REST的Web服務:建立適當的JSON對象在Android的一個ASP .NET Web服務
public class DeviceInfo {
public string Model { get; set; }
public string Serial { get; set; }
}
public class DeviceManagerController : ApiController {
...
public string Post([FromBody]DeviceInfo info) {
...
}
}
這裏是我正在構建Android中的JSON對象:
URL url = new URL (url);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.connect();
// Send POST output.
JSONObject jsonParam = new JSONObject();
jsonParam.put("Model", "HP");
jsonParam.put("Serial", "1234");
DataOutputStream printout = new DataOutputStream(urlConn.getOutputStream());
String jsonStr = jsonParam.toString();
String encodedStr = URLEncoder.encode(jsonStr,"UTF-8");
printout.writeChars(encodedStr);
printout.flush();
printout.close();
該代碼成功調用Web服務。但是,參數(DeviceInfo)爲空。
我甚至試着直接傳遞jsonStr而不是先編碼它們。但是,在這種情況下,雖然參數info
不再爲空,但成員Model
和Serial
仍爲空。
我想知道是否有其他東西,我錯過了。問候。
謝謝您的幫助。但是,您的答案有點誤導。 JSONObject與Android SDK一起提供,因此您不需要使用外部庫。 – Peter
是的,它提供了,但你應該知道這是最糟糕的方式之一。想象一下,你的dto有100個字段,數組,並且你想用這個內置的json處理機制來解析它到你的對象(包含例如hashmaps,arraylist和任何你想要的)。現在想象它的解析器代碼對象。通過使用外部庫(btw Gson是Google開發的庫),它始終只是創建數據模型,註釋和總是單行PARSING。字面上單行會將json字符串轉換爲您的對象。 –
那麼使用這些庫就好比穿着新鞋子,而不是在沒有它們的玻璃上行走。它可能,但對你不好。它很痛。我沒有毫無道理地推薦它。 –