1

I have some JSON with this schema:

{
    "person":{
        "name":"test",
        "family":"testi"
    },
    "Employee":{
        "id":54,
        "department":"web development",
        "skils":[{"type":"C#", "grade":"good"},{{"type":"SQL", "grade":"Expert"}}]
    }
}

and I need to map this JSON to following classes:

class Employee {
    public int id { get; set; }
    public string Name { get; set; }
    public string Family { get; set; }
    public string Department { get; set; }
    public Skill[] Skills { get; set;}
}

class skill {
    public string Type { get; set; }
    public string Grade { get; set; }
}

Now is there any way to map my JSON schema to my C# object? I am using the Newtonsoft.Json library and am trying to use the JsonProperty attribute like this:

[JsonProperty("Person.Name")]

on my Employee class. But this does not work. Is there any way to solve this problem?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Navid_pdp11
  • 3,487
  • 3
  • 37
  • 65

1 Answers1

1

Your class is not proper for your json. You must equalize properties of class and properties of json object. Your json has a property named person but your class does not have it.

MappedObject mappedObject = JsonConvert.DeserializeObject<MappedObject>(yourJson);

class MappedObject{
    public Person person;
    public Employee employee; 
}

class Person{
    public string name;
    public string family;
}
class Employee {
    public intid{get; set;}
    public string deartment {get; set;}
    public Skill[] skills {get; set;}
}
class skill{
    public string type{get; set;}
    public string grade{get; set;}
}

OR better way you can use dynamic object.

dynamic result = new ExpandoObject();
result = JsonConvert.DeserializeObject(yourJson);
Hakan SONMEZ
  • 2,176
  • 2
  • 21
  • 32
  • i do this ... ant it work very well... my project is a wrapper for other service and i must send object with my own schema.... i can use auto mapper but this cause create an extra step to convert MappedObject to my schema. I want to reduce this step – Navid_pdp11 Nov 27 '16 at 08:45
  • So you should use my first code. – Hakan SONMEZ Nov 27 '16 at 08:52
  • but it does not fill employee name and family Property .... – Navid_pdp11 Nov 27 '16 at 08:54
  • So you can send or use mappedObject.employee but you have to fill them from your json. after filling you do not use them. – Hakan SONMEZ Nov 27 '16 at 08:55
  • There is an error in the `Employee` class. It still contains the `Name` and `Family` property - which are not part of the inital json schema. And - for sake of successful mapping - capitalization of the properties names should be consistent. – Jürgen Röhr Nov 27 '16 at 09:07