【问题标题】:ASP.NET Service returns JSON data with xml headerASP.NET 服务返回带有 xml 标头的 JSON 数据
【发布时间】:2013-12-19 17:28:00
【问题描述】:

我有这个代码在服务中

 [WebMethod]        
 [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
 public string GetJson(int nNumResults)
 System.Web.Script.Serialization.JavaScriptSerializer serializer = new
        System.Web.Script.Serialization.JavaScriptSerializer();
        List<Dictionary<string, object>> rows =
          new List<Dictionary<string, object>>();
        Dictionary<string, object> row = null;

    // load dataset from sql query (source not posted here)

        DataSet dset = new DataSet();
        dadapter.Fill(dset);

        if (dset.Tables[0].Rows.Count < 1)
        {
            conn1.Close();
            return null;
        }
        conn1.Close();            

        foreach (DataRow dr in dset.Tables[0].Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn col in dset.Tables[0].Columns)
            {
                row.Add(col.ColumnName.Trim(), dr[col]);
            }
            rows.Add(row);
        }
        return serializer.Serialize(rows);
    }

一切正常,只是返回的字符串是带有

的json
<string xmlns="http://www.mysite.com/service"> 

</string> 

最后。如果我删除这些标签,则可以毫无问题地解析 json。

如何获取开头和结尾没有xml标签的json字符串?

我使用来自 Android 的这个请求,它没有读取有效的 JSON:

 Map<String, Object> params = new HashMap<String, Object>();
    params.put("nNumQuotes", "100");                                   

    aq.ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {

        @Override
        public void callback(String url, JSONObject json, AjaxStatus status) {

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

        }
    });

并且还通过集成服务测试从浏览器进行测试,结果相同。

【问题讨论】:

    标签: asp.net xml json service


    【解决方案1】:

    您的请求中是否包含 content-type 标头?

    contentType: "application/json; charset=utf-8"
    

    【讨论】:

      【解决方案2】:

      您应该将“accept: application/json;”添加到您的标头中,以确保服务器知道您希望您的数据返回为 JSON,只要您的 Web 服务实际上可以返回 JSON 格式的数据。

      当您在浏览器中测试 REST Web 服务时(至少在 chrome 中),它会将标头中的“接受类型”设置为:

      Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
      

      通过使用 Fiddler 之类的工具进行测试,您可以将其更改为:

      Accept: application/json
      

      这可以告诉 Web 服务以 JSON 格式返回数据。您正在使用的 android 代码可能没有指定它需要 JSON 数据。同样,您可以使用 fiddler 来查看 android 代码请求的样子。

      我刚刚看到这篇关于类似问题的帖子:ASP.NET JSON web service always return the JSON response wrapped in XML

      【讨论】:

        猜你喜欢
        • 2012-02-26
        • 2023-04-05
        • 1970-01-01
        • 2012-06-20
        • 1970-01-01
        • 1970-01-01
        • 2014-04-17
        相关资源
        最近更新 更多