2

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?

4
  • If possible try to change the json format?... If employees is a collection shouldn't it be represented as one? Good design = (can lead to) good code. Bad design.....not.. Commented Dec 21, 2017 at 13:48
  • 3
    I realise that you probably didn't design the JSON, but can I vote that we find whoever did design that layout, and teach them the error of their ways? Commented Dec 21, 2017 at 13:49
  • In Json, An arry or list is respresented as [], [ elements ] With values separated by comas. Commented Dec 21, 2017 at 13:50
  • We are using this to feed to google visualization, the api expects this kind of json input. Serializing is fine, i can do deserilization as well, just looking for a simpler/ cleaner approach Commented Dec 22, 2017 at 14:11

2 Answers 2

1

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>());
}
Sign up to request clarification or add additional context in comments.

Comments

0

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"
        }]
    }
}

1 Comment

No its as per requirement, while serializing i intentionally added the list index as the node, i am able to serialize, i want to have a functionality to deserialize the same.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.