从 android 服务调用收到的 JsonObject 在 .net 服务中为空

本文关键字:服务 net JsonObject android 调用 | 更新日期: 2023-09-27 18:34:09

我在 MVC 中编写了一个服务 asp.net 该服务接受字符串化的 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;
}

这就是我从安卓发送 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 一样进行 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 来消耗网络服务时,我都会收到空。

错误是什么??

提前感谢您的帮助

从 android 服务调用收到的 JsonObject 在 .net 服务中为空

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

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

se.setDataType("json");
你需要

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();
    }