Reputation: 241
Could someone point me in the right direction on how to tackle a case like this?
I am receiving very "flat" json data such as
{"Color":"Red", "Number":"7", "Name":"Bob"}
however in .NET I have two classes like this:
Class Person
{
[JsonProperty(PropertyName="Name")]
public personName {get;set;}
[//HOW DO I DO THIS HERE???]
public ColorInfo favoriteColor {get;set;}
}
Class ColorInfo
{
public String color {get;set;}
}
So as you can see, I am getting data that doesn't match any part of my object. To tackle basic things, I just do JsonProperty and that will map one to the other (so Name in json maps to personName perfectly). However what about a case where my class has a property of type ColorInfo (a custom class) and THAT class has a property called color?
I need to somehow travel into the color class and assign that color property to the on in json.
Does anyone have thoughts?
Thanks!
Upvotes: 0
Views: 317
Reputation: 10865
Use CustomCreationConverter
, the code is simpler:
public class PersonConverter : JsonCreationConverter<Person>
{
protected override Person Create(Type objectType, JObject jObject)
{
if (FieldExists("favoriteColor ", jObject))
{
return new Person() { favoriteColor = new ColorInfo() { Color = "Red" };
}
}
private bool FieldExists(string fieldName, JObject jObject)
{
return jObject[fieldName] != null;
}
}
Then:
var serializedObject = JsonConvert.SerializeObject( personInstance);
JsonConvert.DeserializeObject<Person>( serializedObject , new PersonConverter());
Upvotes: 3