Reputation: 44288
lets say I have
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
}
now, if I create an anonymous type like...
var p = new Person() {FirstName = "bob",
LastName = "builder",
PhoneNumber = "0800 YESWECAN"};
var anon = new {p.FirstName, p.LastName};
with JSON.NET, when you have TypeNameHandling = TypeNameHandling.Objects, it will serialize ( and then use for deserilization ) the type. What I'm wanting to do, is to fake the type in the annoymous class so that when it gets serialized it looks like a "Person" object.
Is there a nice simple way to do this?
NOTE: It MUST have the Json.Net type information in the json ( $type ). So LBs answer doesn't solve the problem, in fact I could just use the .net frameworks json facilities to do exactly that.
Upvotes: 3
Views: 3629
Reputation: 44288
to fake it, I can introduce a contract to change a property name when outputting the json... eg...
public class FakeTypeContractResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
return propertyName == "_type_" ? "$type" : propertyName;
}
}
so if you have json.net deserializer settings set to
TypeNameHandling = TypeNameHandling.Objects
TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
you can make an annoymous type like the following,
var x = new
{
_type_ = typeof(Person).AssemblyQualifiedName,
p.FirstName,
p.LastName
}
Which will pretend to be a "Person" in the type information, meaning if you deserialize it you will get a person object.
NOTE: the serializer to json settings must be set not to serialize out type information when you are faking it.
Upvotes: 2
Reputation: 116098
You can serialize as
string str = JsonConvert.SerializeObject(new { FirstName = "aaa", LastName = "bbb" })
and you will get a string which looks like Person object
{"FirstName":"aaa","LastName":"bbb"}
Since Json doesn't contain type informations you can deserialize it back to Person
var person = JsonConvert.DeserializeObject(str, typeof(Person));
Upvotes: 3