【问题标题】:Android connecting - WCF Service should return JSONAndroid 连接 - WCF 服务应返回 JSON
【发布时间】:2010-09-12 21:21:34
【问题描述】:

我正在将我的 Android 应用程序连接到 wcf 服务,在我的 Log.i 中,我可以看到它返回的数据正确,我唯一想将其作为 JSON 处理,但我的服务以 XML 形式发送——(我认为):应用中的代码如下所示:

if (entity != null) 
{
    InputStream instream = entity.getContent();  
    BufferedReader reader = new BufferedReader(new InputStreamReader(instream));  
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null){
        sb.append(line + "n");  
    }      

    String result = sb.toString();  
    Log.i(TAG,result);  
    instream.close();  

    JSONObject json=new JSONObject(result);  

    JSONArray nameArray=json.names();  
    JSONArray valArray=json.toJSONArray(nameArray);  

我的示例方法看起来像这样,我不知道如何从 WCF 网络服务返回正确的 JSON 数据:

/// <returns>An enumeration of the (id, item) pairs. Returns null if no items are present</returns>
protected override IEnumerable<KeyValuePair<string, SampleItem>> OnGetItems()
{
    // TODO: Change the sample implementation here
    if (items.Count == 0)
    {
        items.Add("A", new SampleItem() { Value = "A" });
        items.Add("B", new SampleItem() { Value = "B" });
        items.Add("C", new SampleItem() { Value = "C" });
    }
    return this.items;
}

这是我得到的错误: 09-12 17:11:04.924: WARN/System.err(437): org.json.JSONException: Value

【问题讨论】:

    标签: c# android json wcf


    【解决方案1】:

    添加:

     [WebGet(ResponseFormat = WebMessageFormat.Json)]
    

    作为 WCF 服务方法的属性。如果您不使用 GET 请求调用服务,请将 WebGet 更改为 WebInvoke。

    【讨论】:

    • 如果我在使用帖子?我应该使用 WebInvoke
    • 还是不行,我在方法的顶部插入了webget,它没有返回json对象,我仍然可以在浏览器中打开它,它显示为xml
    • 你需要把它放在实际的服务方法上,你的方法看起来不像WCF接口中定义的实际方法(否则,为什么要覆盖?)
    【解决方案2】:

    这看起来像 WCF REST Starter Kit(REST 集合模板)中的代码,因此它应该已经支持 XML 和 JSON。它是您在客户端指定的服务 URI,它返回 XML 或 JSON 表示。默认情况下,它发送 XML,但如果您将“?format=json”放在服务 URI 的 and 中,它会以 JSON 格式发送资源。

    您可以通过使用 ATOM 中返回的服务的内置描述(如果我没记错的话)和 /help after service URI 来获取有用的信息 就像是: http://localhost/servicetest/Service.svc/help

    【讨论】:

      【解决方案3】:

      这就是 wcf 服务方法的样子:它返回一个值的集合。我添加了[WebGet(ResponseFormat = WebMessageFormat.Json)],但它仍然无法正常工作。

      [WebGet(ResponseFormat = WebMessageFormat.Json)]
          protected override IEnumerable<KeyValuePair<string, SampleItem>> OnGetItems()
          {
              // TODO: Change the sample implementation here
              if (items.Count == 0)
              {
                  items.Add("A", new SampleItem() { Value = "A" });
                  items.Add("B", new SampleItem() { Value = "B" });
                  items.Add("C", new SampleItem() { Value = "C" });
              }
              return this.items;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-11
        相关资源
        最近更新 更多