【问题标题】:JSON String returned from SOAP web service containing no records for table从 SOAP Web 服务返回的 JSON 字符串不包含表的记录
【发布时间】:2011-11-21 14:46:14
【问题描述】:

我有一个使用 .NET 框架实现的 SOAP Web 服务 (.asmx),它以这种形式返回一个 JSON 字符串:

{"checkrecord":[{"rollno":"abc2","percentage":40,"attended":12,"missed":34}],"Table1":[]}

现在在我的 Android 应用程序中,我使用 ksoap 通过以下方式调用 Web 服务:

    public String getjsondata(String b)
{       

     String be=""; 

        SoapObject request = new SoapObject(namespace, method_NAME);      
        request.addProperty("rollno",b);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
        envelope.dotNet = true; 
        envelope.setOutputSoapObject(request);

        HttpTransportSE  android = new HttpTransportSE(url);

        android.debug = true; 

 try 
 {

    //android.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");   
    android.call(soap_ACTION, envelope);

    SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
    Log.i("myapp",result.toString());
    System.out.println(" --- response ---- " + result); 
    be=result.toString();

    if (be.startsWith("[")) 
    { // if JSON string is an array
        JSONArr = new JSONArray(be);

        System.out.println("length" + JSONArr.length());
        for (int i = 0; i < JSONArr.length(); i++) 
        {
            JSONObj = (JSONObject) JSONArr.get(i);
            bundleResult.putString(String.valueOf(i), JSONObj.toString());
            System.out.println("bundle result is"+bundleResult);
        } 

     }

   }
    catch (SocketException ex) { 
    ex.printStackTrace(); 
    } catch (Exception e) { 
    e.printStackTrace(); 
    } 


    return be;      


 }

我收到回复,但回复不包含任何记录并显示空白值。

这是来自 Logcat 的回复:

 11-21 20:13:03.283: INFO/myapp(1173): {"checkrecord":[],"Table1":[]}

 11-21 20:13:03.283: INFO/System.out(1173):  --- response ---- {"checkrecord":[],"Table1":[]}

谁能告诉我为什么会这样?

我的网络服务代码:

      using System;
      using System.Collections;
      using System.ComponentModel;
      using System.Data;
      using System.Linq;
      using System.Web;
      using System.Web.Services;
      using System.Web.Services.Protocols;
      using System.Xml.Linq;
      using System.Data.SqlClient;

namespace returnjson
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
    [WebMethod]

    public String getdata(String rollno)
    {
        String json;
        try
        {

            using (SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123"))
            {

           string select = "select * from checkrecord where rollno=\'" + rollno + "\'";
                SqlDataAdapter da = new SqlDataAdapter(select, myConnection);
                DataSet ds = new DataSet();
                da.Fill(ds, "checkrecord");
                DataTable dt = new DataTable();
                ds.Tables.Add(dt);
                json = Newtonsoft.Json.JsonConvert.SerializeObject(ds);

            }
        }

        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return null;

        }

        return json;

      }

    }
 }

编辑:我已经使用 .NET 上的客户端应用程序测试了我的 Web 服务代码,它工作正常..根据返回的 JSON 字符串以及所有记录和值获得正确的响应。

【问题讨论】:

  • 你确定服务器的答案是那个字符串吗?
  • @njzk2 : 是的,当然没有疑问 :-)
  • 好吧,如果 Web 服务正在为另一个客户端工作,则请求或响应逻辑不正确 - 使用 TCPMON 比较工作和非工作客户端,并发布您的结果。

标签: android json web-services android-ksoap2


【解决方案1】:

这个问题似乎与某些特定符号有关:\ 导致肥皂解析错误。

您可以使用诸如 Ethereal 之类的工具来分析输入流并确保您已正确接收。如果它是正确的,也许你应该对你的 json 数据进行编码然后发送它。

我只是在我的服务器(灯)上测试它,它在正文中返回一个 JSONObject,android 使用下面的代码,正常工作:

public static void testApi() {
        AndroidHttpTransport androidHttptt = new AndroidHttpTransport("http://172.16.0.178/1mobile/market/services.php");
        SoapObject request = new SoapObject(NAMESPACE, "check_error");
        // request.addProperty("data", "empty");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        Element[] header = new Element[1];
        header[0] = new Element().createElement(NAMESPACE, "Credentials");
        envelope.dotNet = true;
        envelope.headerOut = header;
        envelope.setOutputSoapObject(request);

        AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(url);
        androidHttpTransport.setXmlVersionTag(XML_HEAD);
        try {
            androidHttptt.call("http://172.16.0.178/check_error", envelope);
            SoapObject response = (SoapObject) envelope.getResponse();
            Log.e("response", "response=" + response.toString());
        } catch (Exception e) {

        }
    }

使用 Etheral,我得到如下数据:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:check_errorResponse xmlns:ns1="http://test.test.com">
<Result xsi:type="xsd:string">{&quot;checkrecord&quot;:[{&quot;rollno&quot;:&quot;abc2&quot;,&quot;percentage&quot;:40,&quot;attended&quot;:12,&quot;missed&quot;:34}],&quot;Table1&quot;:[]}</Result>
</ns1:check_errorResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

可以发现json数据已经转换成

{&quot;checkrecord&quot;:[{&quot;rollno&quot;:&quot;abc2&quot;,&quot;percentage&quot;:40,&quot;attended&quot;:12,&quot;missed&quot;:34}],&quot;Table1&quot;:[]}

【讨论】:

  • 是的,根据你的描述,我认为是soap无法正常解析json数据
  • 好的,但是你能给我一个 SOAP Web 服务编码 JSON 并返回 JSON 字符串的例子吗?我已经在我的帖子上发布了我的网络服务代码。如果要进行编码,您可以建议对其进行修改吗?
  • @notenking 如果你真的在使用 Ethereal,你可能希望升级。我们在 2006 年将项目重命名为 Wireshark。:)
  • @notenking:我从 Web 服务返回的字符串正如我所提到的。我不明白为什么它显示空记录。你说这可能是 / 解析错误,但如果是这种情况,我不会得到任何回应,对吧?
  • JObject o=new JObject.parse(json) -> 这可以帮助我将 JSON 字符串转换为可以返回到我的 Android 应用程序的 JSONObject 吗?
【解决方案2】:

SOAP 协议使用 XML 作为通信手段。您的请求将被转换为 XML 字符串,来自服务器的响应将是一个 XML 字符串,KSOap 会解析该字符串并为您提供一个对象。 所以看起来 WebService 的响应很好,但是 KSoap 解析存在问题。因此,正如你们讨论的那样,您可以在服务器中对字符串进行编码并返回它。 Android 已经提供了对 Base64 编码/解码的支持。

在 web 服务中返回以下内容而不是 json。

Convert.ToBase64String (Encoding.UTF8.GetBytes (json));

这将返回一个编码字符串。因此,您将得到的响应是一个编码字符串。所以在android客户端。

new String(android.util.Base64.decode(responseString.getBytes(),android.util.Base64.DEFAULT))

这会给你解码后的字符串。希望对你有帮助

【讨论】:

  • 我试过了,但还是没有用同样的问题?顺便说一句,解码后字符串会是什么格式?会是 base64 吗?
  • 再次检查 WebService 是否正常返回。解码后将是 JSON 字符串。您已在服务器端将 JSON 字符串编码为 Base64 字符串并对其进行解码以获取 JSON 字符串
  • 这是我在解码之前和之后在 logcat 中得到的:pastie.org/2937838 ..web 服务工作正常..它在服务器端正确返回编码字符串..但是服务器端编码字符串和客户端侧响应字符串不匹配,因为响应包含空记录
  • SoapSerializationEnvelope 信封 = 新 SoapSerializationEnvelope(SoapEnvelope.VER11);信封.setOutputSoapObject(请求); HttpTransportSE httpTransport=new HttpTransportSE(soapURL); httpTransport.call(soapAction, 信封);对象 resultsRequestSOAP = envelope.getResponse();试试这个我用它来调用网络服务。我得到了正确的字符串
猜你喜欢
  • 2013-04-08
  • 1970-01-01
  • 2015-03-26
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
  • 2014-01-03
  • 1970-01-01
  • 2019-07-25
相关资源
最近更新 更多