10

リストリターン型の関数があります。私はこれを次のようなJSON対応のWebサービスで使用しています。

  [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<Product> GetProducts(string dummy)  /* without a parameter, it will not go through */
    {
        return new x.GetProducts();
    }

これは次を返します:

{"d":[{"__type":"Product","Id":"2316","Name":"Big Something ","Price":"3000","Quantity":"5"}]}

このコードを単純なaspxファイルでも使用する必要があるため、JavaScriptSerializerを作成しました。

        JavaScriptSerializer js = new JavaScriptSerializer();
        StringBuilder sb = new StringBuilder();

        List<Product> products = base.GetProducts();
        js.RegisterConverters(new JavaScriptConverter[] { new ProductConverter() });
        js.Serialize(products, sb);

        string _jsonShopbasket = sb.ToString();

ただし、タイプなしで返されます。

[{"Id":"2316","Name":"Big One ","Price":"3000","Quantity":"5"}]

誰かが最初のように2番目のシリアル化を機能させる方法の手がかりを持っていますか?

ありがとう!

4

3 に答える 3

16

JavaScriptSerializer を作成するときに、それに SimpleTypeResolver のインスタンスを渡します。

new JavaScriptSerializer(new SimpleTypeResolver())

独自の JavaScriptConverter を作成する必要はありません。

于 2009-08-14T14:27:25.857 に答える
3

OK、解決策があります。__typeをJavaScriptConverterクラスのコレクションに手動で追加しました。

    public class ProductConverter : JavaScriptConverter
{        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        Product p = obj as Product;
        if (p == null)
        {
            throw new InvalidOperationException("object must be of the Product type");
        }

        IDictionary<string, object> json = new Dictionary<string, object>();
        json.Add("__type", "Product");
        json.Add("Id", p.Id);
        json.Add("Name", p.Name);
        json.Add("Price", p.Price);

        return json;
    }
}

これを行う「公式の」方法はありますか?:)

于 2009-06-22T13:25:40.703 に答える
2

ジョシュアの答えに基づいて、 SimpleTypeResolver を実装する必要があります

これが私のために働いた「公式」の方法です。

1) このクラスを作成します

using System;
using System.Web;
using System.Web.Compilation;
using System.Web.Script.Serialization;

namespace XYZ.Util
{
    /// <summary>
    /// as __type is missing ,we need to add this
    /// </summary>
    public class ManualResolver : SimpleTypeResolver
    {
        public ManualResolver() { }
        public override Type ResolveType(string id)
        {
            return System.Web.Compilation.BuildManager.GetType(id, false);
        }
    }
}

2)それを使用してシリアル化します

var s = new System.Web.Script.Serialization.JavaScriptSerializer(new XYZ.Util.ManualResolver());
string resultJs = s.Serialize(result);
lblJs.Text = string.Format("<script>var resultObj = {0};</script>", resultJs);

3)それを使用して逆シリアル化します

System.Web.Script.Serialization.JavaScriptSerializer(new XYZ.Util.ManualResolver());
var result = json.Deserialize<ShoppingCartItem[]>(jsonItemArray);

完全な投稿はこちら: http://www.agilechai.com/content/serialize-and-deserialize-to-json-from-asp-net/

于 2010-04-23T19:32:29.857 に答える