我在asp.net MVC中编写了一个服务,它接受字符串化的Json对象作为参数,我试图从我的android代码中消费
这是服务方法
public JsonResult saveDataInSession(string jsonObjSend)
{
JsonResult jsonResult = null;
List<OnlineUserDetails> lstValue = new List<OnlineUserDetails>();
OnlineUserDetails UserDetails = new OnlineUserDetails();
JavaScriptSerializer jss = new JavaScriptSerializer();
UserDetails = JsonConvert.DeserializeObject<OnlineUserDetails>(jsonData);
UserDetails.LoginId = UserDetails.EmaillId;
UserLoginAndSignUp UserLoginAndSignUp = new UserLoginAndSignUp();
string result = UserLoginAndSignUp.SaveDetails(UserDetails);
jsonResult = Json(UserDetails, JsonRequestBehavior.AllowGet);
return jsonResult;
}
这就是我从android
发送json对象的方式jsonObjSend = new JSONObject();
try{
jsonObjSend.put("FirstName", firstname.getText().toString());
jsonObjSend.put("LastName", lastname.getText().toString());
jsonObjSend.put("EmaillId", emailid.getText().toString());
jsonObjSend.put("Password", password.getText().toString());
jsonObjSend.put("MobileNumber", mobilenumber.getText().toString());
//jsonObjSend.put("Login_RememberMe", "true");
//
}catch (JSONException e) {
e.printStackTrace();
}
进行HttpRequest调用,如
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se=null;
try {
se = new StringEntity(jsonObjSend.toString(),HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
se.setContentType("application/json");
se.setContentEncoding("UTF-8");
// Set HTTP parameters
httpPostRequest.setEntity(se);
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
但是每当我尝试通过传递jsonobject来使用webservice时,我都会收到null。
错误是什么?
提前感谢您的帮助
答案 0 :(得分:0)
我认为在与json数据一起发布请求时需要设置 dataType = json
在你的情况下,我认为可以选择这样的话:
se.setDataType("json");
答案 1 :(得分:0)
您需要将ByteArrayEntity
而不是StringEntity
传递给`httpPostRequest.setEntity()
请尝试以下代码:
HttpPost request = new HttpPost(url);
request.addHeader("Content-Type", "application/json");
HttpResponse response;
try {
request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
response = mHttpClient.execute(request);
String jsonString = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
e.printStackTrace();
}