It's worth considering the JSON you want.
Assuming you have this class
class Person
{
public string Name { get; set; }
public PhoneNumber HomePhone { get; set; }
}
You want this serialized to JSON, like this
{ "Name":"Joe", "HomePhone": "555-555-555" }
But you are getting JSON, something like this
{ "Name":"Joe","HomePhone": {"Number": "555-555-555"} }
--
To see why this is so, consider that the property Number of Person is an object. JSON is going to expect at least a {} to wrap the object - or more to the point, a set of name/values within the {}.
If you really, really want the former JSON syntax you need to register a custom converter for the Person object so that you can convince it to serialize and deserialze as a string. (see code example below).
However, I'd recommend that you just accept that because PhoneNumber is an object it correspond to a name/value dictionary when serialized into JSON and accept that the JSON is going to look a little less 'clean' than you might ideally want.
FWIW here's a code example that achieves your original aim (not the recommended approach)..
class Person
{
public string Name { get; set; }
public PhoneNumber HomeNumber { get; set; }
}
struct PhoneNumber
{
private string _number;
public PhoneNumber(string number)
{
_number = number;
}
public override string ToString()
{
return _number;
}
}
class PersonConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { yield return typeof(Person); }
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
Person person = obj as Person;
if (person != null)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict["Name"] = person.Name;
dict["HomeNumber"] = person.HomeNumber.ToString();
return dict;
}
return new Dictionary<string, object>();
}
public override object Deserialize(IDictionary<string, object> dict, Type type, JavaScriptSerializer serializer)
{
if (dict == null)
throw new ArgumentNullException("dict");
if (type == typeof(Person))
{
// Deserialize the Person's single property.
string name = (string)dict["Name"];
string homeNumber = (string)dict["HomeNumber"];
// Create the instance to deserialize into.
Person person = new Person()
{
Name = name,
HomeNumber = new PhoneNumber(homeNumber)
};
return person;
}
return null;
}
}
class Program
{
static void Main(string[] args)
{
PhoneNumber number = new PhoneNumber("555 555");
Person joe = new Person() { Name = "Joe", HomeNumber = number };
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new PersonConverter() });
Console.Out.WriteLine(serializer.Serialize(joe));
}
}