繁体   English   中英

通过Java Android消费RESTful C#Web服务

[英]Consuming RESTful C# Web Service through Java Android

亲爱的,

我知道标题似乎很流行而且很容易,但是我所面对的却太奇怪了。

简而言之,我在服务器上发布了RESTful C#.NET 4.0 Web服务,我想通过Java在Android应用程序中使用它,容易吗?

问题是:每当我调用.NET Web服务并获得响应时,java都无法将返回字符串解析为Json。

错误信息:

org.json.JSONException: Value {lhs:"1 Euro",rhs: "1.3711 U.S. dollars",error: "",icc: true} of type java.lang.String cannot be converted to JSONObject
    at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:158)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.itrack21.mobileapp.LoginActivity.getUserInfo(LoginActivity.java:151)
at com.itrack21.mobileapp.LoginActivity$1$1.run(LoginActivity.java:114)
at java.lang.Thread.run(Thread.java:841)
threadid=17: thread exiting with uncaught exception (group=0x4164d700)

Java代码:

public void getRate(String link) {

        try {
                URL url = new URL(link);
                URLConnection connection = url.openConnection();
                InputStream str = connection.getInputStream();
                InputStreamReader reader = new InputStreamReader(str);
                BufferedReader bufReader = new BufferedReader(reader);
                String line=new String();
                StringBuffer buffer = new StringBuffer();

                while( (line=bufReader.readLine()) != null) {
                    buffer.append(line);
                }

            JSONObject obj = null;
            try {
                obj = new JSONObject(buffer.toString());
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            String rhs = "";
            try {
                rhs = obj.getString("rhs");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Log.i("getRate","Converted Currency = " + rhs.toString());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

调试:

我做了很多调试方案,但是没有运气,这里我将用最奇怪的一种来描述问题。

  1. 我使用Java代码通过以下链接http://www.google.com/ig/calculator?hl=en&q=1USD=?EUR使用Google Web服务进行货币转换,并且得到如下响应: {lhs: "1 US dollar",rhs: "0.726321906 Euros",error: "",icc: true} 在这里,我的代码运行完美。

  2. 我从Google Web服务复制了确切的Json值返回值,并且可以很好地使用我的代码,然后将其作为RESTful C#服务中的HARD CODED字符串返回,如下所示:

C#代码:

public string GetInfo()
{
return "{lhs:\"1 Euro\",rhs: \"1.3711 U.S. dollars\",error: \"\",icc: true}";
}
  1. 我使用与调用Google Web服务所用的代码相同的代码来请求C#.NET Web服务,但在org.json.JSONException: Value {lhs:"1 Euro",rhs: "1.3711 US dollars",error: "",icc: true} of type java.lang.String cannot be converted to JSONObject at org.json.JSON.typeMismatch(JSON.java:111)上面列出了错误, org.json.JSONException: Value {lhs:"1 Euro",rhs: "1.3711 US dollars",error: "",icc: true} of type java.lang.String cannot be converted to JSONObject at org.json.JSON.typeMismatch(JSON.java:111)我在上面列出了错误org.json.JSONException: Value {lhs:"1 Euro",rhs: "1.3711 US dollars",error: "",icc: true} of type java.lang.String cannot be converted to JSONObject at org.json.JSON.typeMismatch(JSON.java:111)

  2. 当我将返回值作为HARD CODE复制并粘贴到我的代码中时,它就可以正常工作。

     JSONObject obj = null; try { obj = new JSONObject("{lhs:\\"1 Euro\\",rhs: \\"1.3711 US dollars\\",error: \\"\\",icc: true}"); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } 

完成了许多“疯狂”的调试方案,包括更改服务器本身,但是没有运气。

我做错了什么?

问候,

在JSON中,您也需要将密钥包装在引号中。 因此:

{lhs: "1 US dollar",rhs: "0.726321906 Euros",error: "",icc: true}

您将必须执行以下操作:

{"lhs": "1 US dollar","rhs": "0.726321906 Euros","error": "","icc": "true"}

您可以通过以下网址在线检查JSON: http//jsonlint.com/

经过长时间的调试,我找到了原因,然后找到了解决方案。 开始了:

  1. 通过Chrome浏览器访问Google Maps Web服务 ,您将得到Json的响应。 为了进行调试,请右键单击页面,然后选择View page source 请注意,Json的字符串是纯Json,没有添加。

  2. 当您通过Chrome浏览器对C#.NET响应重复相同的过程时,您会注意到该响应不是纯粹的Json,它被以下内容包围: <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">{JSON String HERE}</string>

解:

要删除响应周围的字符串,您必须将Json字符串作为System.IO.Stream返回。 所需的代码在这里更改:

public System.IO.Stream GetInfo()
{
    OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse;
    context.ContentType = "text/plain";
    return new System.IO.MemoryStream(ASCIIEncoding.Default.GetBytes("{lhs:\"1 Euro\",rhs: \"1.3711 U.S. dollars\",error: \"\",icc: true}"));
}

这个解决方案对我来说很好用,但这是最佳解决方案吗? 从对象转换为Json,然后从Json字符串转换为字节几乎没有开销,怎么办? 建议?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM