Freephone Panwal
Freephone Panwal

Reputation: 1591

Unable to serialize object using Javasciptserializer

I'm trying to serialize an object to JSON string as shown below:

new JavaScriptSerializer().Serialize(person)

Here, person is the object which is having lot of attributes such as name, address, city, state, etc but I have decorated the class as shown below so that it'll serialize only name and address.

using System;
using System.Runtime.Serialization;

namespace DataAccess.Models
{
    [Serializable]
    [DataContract]
    public class Person
    {        
    public string Id { get; set; }

    [DataMember(Name = "full-name")]
    public string Name { get; set; }

    [DataMember(Name = "address")]
    public string Address { get; set; }

    public string City { get; set; }

    public string State { get; set; }

    public string Zip { get; set; }

    }
}

But when I run the program, the new JavaScriptSerializer().Serialize(person) gives me JSON with all the data including Id, City, State, Zip.

Why is it not giving me only full-name & address? It seems like it is completely ignoring these DataMember attributes.

When I use JsonConvert.SerializeObject(person) from Newtonsoft, everything works perfect & it serializes only Name & Address but JavascriptSerializer is giving all data.

Can any one tell me what could be the issue?

Upvotes: 0

Views: 370

Answers (1)

xDaevax
xDaevax

Reputation: 2022

Consider using the [ScriptIgnore()] Attribute on those properties you don't want to be serialized.

http://msdn.microsoft.com/en-us/library/system.web.script.serialization.scriptignoreattribute(v=vs.100).aspx

See here for a detailed list of how the JavaScriptSerializer will handle different types: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=vs.110).aspx

Edit:
Note that the JavascriptSerializer is not aware of the DataMember attributes and they therefore will not be used by the JavascriptSerializer (JSON.net will use them, but JSON.Net also defines it's own constructs for this: [JsonIgnore()] [JsonObject] and many other attributes support custom-naming). To accomplish this, try using the DataContractJsonSerializer in the System.Runtime.Serialization.Json namespace with some draw-backs.

See this question and answer for additional information:

JavaScriptSerializer.Deserialize - how to change field names

Upvotes: 1

Related Questions