13

何が欠けているのか、どこが間違っているのかわかりません。

ASP.NET 2.0(.Net 3.5フレームワーク上)Webアプリケーションを構築しており、Webサービスを組み込んでいます。これはMVCプロジェクトではないことに注意してください。JSON文字列を返すメソッドを公開したいと思います。jqGridjQueryプラグインをフィードするようにフォーマットされています。

これは、私がサービスに実装した予備テスト方法です。(Phil HaackのMVCガイド)に感謝します。

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getData()
{
    JavaScriptSerializer ser = new JavaScriptSerializer();

    var jsonData = new
    {
        total = 1, // we'll implement later 
        page = 1,
        records = 3, // implement later 
        rows = new[]{
          new {id = 1, cell = new[] {"1", "-7", "Is this a good question?", "yay"}},
          new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?", "yay"}},
          new {id = 3, cell = new[] {"3", "23", "Why is the sky blue?", "yay"}}
        }
    };

    return ser.Serialize(jsonData); //products.ToString();
}

呼び出されると、これが返されます(わかりやすくするためにフォーマットされています)。

<?xml version="1.0" encoding="utf-8" ?> 
<string  mlns="http://tempuri.org/">
{
  "total":1,
  "page":1,
  "records":3,
  "rows":
    [
      {"id":1,"cell":["1","-7","Is this a good question?","yay"]},
      {"id":2,"cell":["2","15","Is this a blatant ripoff?","yay"]},
      {"id":3,"cell":["3","23","Why is the sky blue?","yay"]}
    ]
}
</string> 

xmlラッピングなしで上記の応答をどのように達成しますか?

4

6 に答える 6

10

コードでは、jsonを「返さない」でください。代わりに使用してください:

Context.Response.Write(ser.Serialize(jsonData));

その後、あなたは元気になります。

通常のreturnコマンドは、より適切なサービス形式を入力することで役立ちます。これを使用して、クライアントでjsonをこの形式からアンラップする方がよいと言う人もいます。私は言う、ちょうどあなたがそれを使いたいように正確にものを吐き出す!

于 2010-01-13T16:53:57.203 に答える
10

あなたがしていないかもしれない3つのこと:

  • メソッドを静的にマークする
  • POSTの実行
  • jQueryのデータに空の「{}」を渡します。

GETを使用してメソッドを呼び出す方法があるかもしれませんが、私はこれまでPOSTのみを使用しました。私はあなたの例をこれで動作させることができました:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
    // In your javascript block
    $(document).ready(function()
    {
        $.ajax({
            url: "/Default.aspx/Tester",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{}",
            success: done
        });
    });

    function done(data)
    {
        // Include http://www.json.org/json2.js if your browser doesn't support JSON natively
        var data = JSON.parse(data.d);
        alert(data.total);
    }
</script>

コードビハインド(Webサービスを作成する必要はありません。これをdefault.aspxに入れることができます):

[WebMethod]
public static string Tester()
{
    JavaScriptSerializer ser = new JavaScriptSerializer();

    var jsonData = new
    {
        total = 1, // we'll implement later 
        page = 1,
        records = 3, // implement later 
        rows = new[]{
              new {id = 1, cell = new[] {"1", "-7", "Is this a good question?", "yay"}},
              new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?", "yay"}},
              new {id = 3, cell = new[] {"3", "23", "Why is the sky blue?", "yay"}}
            }
        };

    return ser.Serialize(jsonData); //products.ToString();
}

結果:

{"d":"{\"total\":1,\"page\":1,\"records\":3,\"rows\":[{\"id\":1,\"cell\":[\"1\",\"-7\",\"Is this a good question?\",\"yay\"]},{\"id\":2,\"cell\":[\"2\",\"15\",\"Is this a blatant ripoff?\",\"yay\"]},{\"id\":3,\"cell\":[\"3\",\"23\",\"Why is the sky blue?\",\"yay\"]}]}"}

より詳細な説明はこちら

于 2010-01-13T17:22:31.457 に答える
2

サービスをScriptServiceとしてマークすると、JSONシリアル化が自動的に処理されます。応答を手動でシリアル化しないでください。詳細については、このスタックオーバーフローエントリを参照してください。

于 2010-01-13T16:56:54.717 に答える
1

JSONを要求し、属性を含めると[ScriptService]、ASP.NETは応答をJSONに自動的にシリアル化します。XMLが表示されているということは、これら2つの前提条件の1つが満たされていないことを示しています。Newtonsoftなどの別のシリアライザーを使用する場合を除いて、JSONに手動でシリアル化するという提案は間違っています。

次に、JSON対応のASMXWebサービスの簡単な実例を示します。

<%@ WebService Language="C#" Class="WebService" %>
using System;
using System.Collections.Generic;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
    [WebMethod]
    public MyClass Example()
    {
        return new MyClass();
    }

    public class MyClass
    {
        public string Message { get { return "Hi"; } }
        public int Number { get { return 123; } }
        public List<string> List { get { return new List<string> { "Item1", "Item2", "Item3" }; } }
    }
}

それを要求して応答を処理するJavaScript(MyClass.MessageからのメッセージでJSアラートをポップアップするだけです):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test</title>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.js" type="text/javascript"></script>  
</head>
<body>
    <script type="text/javascript">
        $.ajax({
            type: "POST",
            url: "WebService.asmx/Example",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{ }",
            error: function (XMLHttpRequest, textStatus, errorThrown) { alert(langError + " " + textStatus); },
            success: function (msg) {
                alert(msg.d.Message);
            }
        });
    </script>
</body>
</html>

Httpリクエスト:

POST http://HOST.com/WebService.asmx/Example HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://HOST.com/Test.aspx
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Connection: Keep-Alive
Content-Length: 3
Host: HOST.com

{ }

HTTP応答:

HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 08 Oct 2013 08:36:12 GMT
Content-Length: 98

{"d":{"__type":"WebService+MyClass","Message":"Hi","Number":123,"List":["Item1","Item2","Item3"]}}

結果:

JSポップアップに「こんにちは」と表示されます。

参照:

https://stackoverflow.com/a/16335022/397817

https://stackoverflow.com/a/3839649/397817

于 2013-10-08T08:59:22.737 に答える
1

私は次のことをすることで幸運に恵まれました:

[WebMethod]
public static void GetDocuments()
{
    HttpContext.Current.Response.ContentType = "application/json";
    HttpContext.Current.Response.Write(JsonConvert.SerializeObject(repository.GetDocuments()));
    HttpContext.Current.Response.End();
}

コンテンツタイプを適切に設定し、JSONを直接応答に書き込んでから、応答を終了して、応答を破損するデータがそれ以上送信されないようにすることが重要です。このアーキテクチャの利点は、必要なシリアライザーを使用できることです。組み込みのJSONシリアライザーに限定されません。この場合、私はJson.NETを使用しました。

私はこれがアーキテクチャを悪用していることを認識しています(そして私は個人的にデータを返すことになっているものに対してvoidリターンタイプを持つことを嫌います)が、これは私が見つけた唯一の本当に信頼できる方法です。

一方、 John Saundersがここで説明している理由から、 WCFまたはWebAPIに切り替える必要があります。特にWebAPIは非常に使いやすく、クライアントとサーバー間のコンテンツタイプのネゴシエーションを可能にします。

于 2014-11-17T15:02:16.313 に答える
1
  1. リターンタイプをvoidに変更します
  2. オブジェクトを^_^に置きます
[WebMethod]
public static void GetDocuments()
{
    HttpContext.Current.Response.ContentType = "application/json";
    HttpContext.Current.Response.Write(JsonConvert.SerializeObject( ^_^ ));
    HttpContext.Current.Response.End();
}
于 2019-05-16T11:48:42.807 に答える