0

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!

1 Answer 1

3

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());
Sign up to request clarification or add additional context in comments.

3 Comments

Wait i'm confused - ColorInfo is not actually a subclass of Person, sorry. I can't return a new ColorInfo in this way. Also is this really the way to do it? I'm having a tough time understanding how this would take a "favoriteColor" string (red, for example) and assigning the ColorInfo's property to the ColorInfo, then assigning ColorInfo to Person. If you could shed a little more light I'd appreciate it :)
Thanks will try - also JsonCreationConverter is a class I'd have to make myself right? It's not native to json.net?
Thank you this did it :) Truly appreciate your assistance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.