Siddhannt Arora
Siddhannt Arora

Reputation: 31

Custom Deserialization using Newtonsoft.json

I am trying to deserialize a json for my class structure

I have the following JSON:

{
    "Main": {
        "Employees": {
            "0": {
                "FirstName": "Test ",
                "LastName": "One"
            },
            "1": {
                "FirstName": "Test ",
                "LastName": "Two"
            }
        }
    }
}    

I want to deserialize it for the following class structure:

public class Main
{
    public List<Employee> Employees { get; set; }
}

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Can someone suggest me how to write a converter for this/ any other option to achieve this?

Upvotes: 2

Views: 457

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062502

Obviously the ideal thing would be to have different JSON to work from (an array), but that might not be possible.

This doesn't use the custom deserialization options, but - it works:

dynamic root = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
Newtonsoft.Json.Linq.JObject emps = root.Main.Employees;
var list = new List<Employee>();
foreach(var child in emps.Properties())
{
    list.Add(child.Value.ToObject<Employee>());
}

Upvotes: 1

Adam Brown
Adam Brown

Reputation: 1729

Your JSON is kind of wrong. You've made an employees type with fields 0 and 1 that happen to both have the same sub-properties. I think what you're actually looking to do is to make Employees an array.

{
"Main" : {
    "Employees": [
        {
            "FirstName": "Test ",
            "LastName": "One"
        },
        {
            "FirstName": "Test ",
            "LastName": "Two"
        }]
    }
}

Upvotes: 0

Related Questions