在构建Android的适当JSON对象为ASP .NET Web服务 [英] Building proper JSON object in Android for an ASP .NET Web service

查看:125
本文介绍了在构建Android的适当JSON对象为ASP .NET Web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下基于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对象的Andr​​oid:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆