简体   繁体   中英

JSON.NET Object Properties

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!

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM