Search code examples
c#jsonvalueinjecter

How to map ValueInjecter using Json Object?


If I have Json object that I want to map to a concrete object, how would I do that?

  public class Student
    {
        public string Name { get; set; }  
    }

  class Program
    {
        static void Main(string[] args)
        {
            var o = new JObject {{"Name", "Jim"}};
            Student student = new Student();


            student.InjectFrom(o);
        }
    }

this results in null. When I expected "Jim" to be set.


Solution

  • Since you're using anyway, you can populate an object directly from JSON using JsonConvert.PopulateObject():

    JsonConvert.PopulateObject(json, student);
    

    Or if you prefer you can add some extensions methods:

    public static class JsonExtensions
    {
        public static void PopulateFromJson<T>(this T target, string json) where T : class
        {
            if (target == null || json == null)
                throw new ArgumentException();
            JsonConvert.PopulateObject(json, target);
        }
    
        public static void PopulateFromJson<T>(this T target, JToken json) where T : class
        {
            if (target == null || json == null)
                throw new ArgumentException();
            using (var reader = json.CreateReader())
                JsonSerializer.CreateDefault().Populate(reader, target);
        }
    }
    

    And do

            var o = new JObject { { "Name", "Jim" } };
            Student student = new Student();
            student.PopulateFromJson(o);