0

我在 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 来使用 web 服务时,我都会收到 null。

有什么错误??

提前感谢您的帮助

4

2 回答 2

0

我认为您需要在发布请求以及 json 数据时设置dataType = json

在你的情况下,我想有一个选项可以调用这样的东西:

se.setDataType("json");
于 2013-10-07T13:32:42.457 回答
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();
    }
于 2013-10-07T13:54:39.717 回答