简体   繁体   中英

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.

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

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