3

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.

chobo2
  • 83,322
  • 195
  • 530
  • 832
  • IIRC, `ValueInjecter` is designed to be used with 2 concrete typed instances. In your example, I doubt `ValueInjecter` can infer the properties from the JSON object. – Metro Smurf Dec 17 '15 at 00:06
  • JObject implements an `IDictionary` that's why you can have some kind of dynamic properties but ValueInjecter is design to map property with the same name, it will not look into the JOject Dictionary – Thomas Dec 17 '15 at 00:20
  • How can I get around that? The Json key has the same name as you can see from my example. – chobo2 Dec 17 '15 at 00:34
  • you need to create a custom Injection by inheriting `KnownSourceInjection` – Omu Dec 17 '15 at 16:02

1 Answers1

0

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);
dbc
  • 104,963
  • 20
  • 228
  • 340