在构建Android的适当JSON对象为ASP .NET Web服务 [英] Building proper JSON object in Android for an ASP .NET Web service
问题描述
以下基于REST的Web服务在编写ASP .NET:
The following REST-based Web Service in written in ASP .NET:
public class DeviceInfo {
public string Model { get; set; }
public string Serial { get; set; }
}
public class DeviceManagerController : ApiController {
...
public string Post([FromBody]DeviceInfo info) {
...
}
}
这里是我如何构建JSON对象的Android:
Here is how I am building the JSON object in Android:
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 ();
这code成功调用Web服务。然而,参数(DeviceInfo)为null。
This code successfully invokes the web service. However, the parameter (DeviceInfo) is null.
我甚至尝试过jsonStr,而不是直接编码首先他们。然而,在这种情况下,虽然参数信息
不再为空,成员模式
和串行
仍然空。
I even tried passing jsonStr directly instead of encoding them first. However, in this case, although the parameter info
is no longer null, the members Model
and Serial
are still null.
我想知道是否还有别的东西,我错过了。问候。
I am wondering if there is something else that I missed. Regards.
推荐答案
使用 OutputStreamWriter
而不是 DataOutputStream类
照顾的问题:
Using OutputStreamWriter
instead of DataOutputStream
takes care of the problem:
OutputStream os = urlConn.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8");
writer.write(jsonStr);
writer.close();
os.close();
这篇关于在构建Android的适当JSON对象为ASP .NET Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!