none
How to deserialize JSON to an C# object RRS feed

  • Question

  • I am able to de-serialize JSON that looks like this:

    {
        'Name': 'Fred',
        'Cars': {
            'Car': [
                {
                    'Make': 'Honda'
                },
                {
                    'Make': 'Ford'
                }
            ]
        }
    }

    into a C# class that looks like this:

        class Car
        {
            public string Make { getset; }
        }
     
        class Cars
        {
            public Car[] Car { getset; }
        }
     
        class CarOwner
        {
            public string Name { getset; }
            public Cars Cars { getset; }
        }
    

    by doing this:

    CarOwner carOwner = JsonConvert.DeserializeObject<CarOwner>(carOwnerJson);
    

    What would the class need to look like if the JSON looked like this instead?

    {
        'Name': 'Fred',
        'Cars': {
            'Car': {
                '0': {
                    'Make': 'Honda'
                },
                '1': {
                    'Make': 'Ford'
                }
            }
        }
    }

    Also, is one or the other JSON format considered better? Is there an advantage of some kind to explicitly calling out the index values as it does in the second version above? Say in terms of doing incremental updates to the JSON?

    Thanks in advance from a newbie,

    Ron Rice


    Ron Rice

    Thursday, January 16, 2014 8:57 PM

Answers

  • Hi r31416,

    The quickest method of converting between JSON text and a .NET object is using the JsonSerializer. The JsonSerializer converts .NET objects into their JSON equivalent and back again by mapping the .NET object property names to the JSON property names and copies the values for you.

    Here is a good artilce about Serializing and Deserializing JSON


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Proposed as answer by Ramya SJ Friday, January 17, 2014 10:34 AM
    • Marked as answer by Eason_H Friday, January 24, 2014 2:24 AM
    Friday, January 17, 2014 2:03 AM