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!

3 Answers 3

16

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

new JavaScriptSerializer(new SimpleTypeResolver())

No need to create your own JavaScriptConverter.

Sign up to request clarification or add additional context in comments.

1 Comment

Any idea of how I can rename the "_type" property to remove the underscore ?
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?:)

Comments

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/

2 Comments

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!
@JayRO-GreyBeard fixed the link

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.