JavaScriptSerializer with custom Type
Asked Answered
M

3

10

I have a function with a List return type. I'm using this in a JSON-enabled WebService like:

  [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();
    }

this returns:

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

I need to use this code in a simple aspx file too, so I created a 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();

but it returns without a type:

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

Does anyone have any clue how to get the second Serialization work like the first?

Thanks!

Mariquilla answered 22/6, 2009 at 13:3 Comment(0)
M
3

Ok, I have the solution, I've manually added the __type to the collection in the JavaScriptConverter class.

    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;
    }
}

Is there any "offical" way to do this?:)

Mariquilla answered 22/6, 2009 at 13:25 Comment(0)
E
16

When you create the JavaScriptSerializer, pass it an instance of SimpleTypeResolver.

new JavaScriptSerializer(new SimpleTypeResolver())

No need to create your own JavaScriptConverter.

Expertise answered 14/8, 2009 at 14:27 Comment(1)
Any idea of how I can rename the "_type" property to remove the underscore ?Nylon
M
3

Ok, I have the solution, I've manually added the __type to the collection in the JavaScriptConverter class.

    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;
    }
}

Is there any "offical" way to do this?:)

Mariquilla answered 22/6, 2009 at 13:25 Comment(0)
C
2

Building on Joshua's answer, you need to implement a SimpleTypeResolver

Here is the "official" way that worked for me.

1) Create this class

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) Use it to serialize

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) Use it to deserialize

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

Full post here: http://www.agilechai.com/content/serialize-and-deserialize-to-json-from-asp-net/

Carlin answered 23/4, 2010 at 19:32 Comment(2)
sharpdeveloper.net is dead. It is so very annoying and frustrating when slogging through a problem to have a potentially headache solving answer on a broken link. Please people! Just copy/paste the info here!Chalcopyrite
@Chalcopyrite fixed the linkCarlin

© 2022 - 2024 — McMap. All rights reserved.