How to serialize/deserialize the following

Here is a snippet of JSON that I need to deserialize into objects, do some limited changes to the objects, and then serialize back to JSON for submitting to a server. To me, the problem is the format of the JSON. But that format won’t be changed.

"{\"SourceID\":\"4\",\"Machines\":{\"2017\":{\"Machine\":{\"Version\":\"501\"}}}}";

2017 is the ID of the machine. So, yeah, it would be much better if they would just update the JSON to reflect that and have it be a key value pair inside the Machine class instead of using the ID as the class type, but they won’t do that. I changed it myself to reflect the change, and then I could create sensible POCOs, and FromJson() and ToJson() work wonderfully.

I don’t want to have a class for every ID. I looked into deserializing to a Dictionary<string,object> and that sort of works, but that is a lot of brittle code, especially given that the schema of the real JSON is more of the same.

Any ideas on how to best approach this?

Gistlyn provides a good playground for running quick explatory snippets like this.

http://gistlyn.com/?gist=32518b6aea880c07d538fde1a974e0b8

public class Dto
{
    public int SourceID { get; set; }
    public Dictionary<int, MachineEntry> Machines { get; set; }
}

public class MachineEntry
{
    public Machine Machine { get; set; }
}

public class Machine
{
    public string Version { get; set; }
}

var json = "{\"SourceID\":\"4\",\"Machines\":{\"2017\":{\"Machine\":{\"Version\":\"501\"}}}}";

var dto = json.FromJson<Dto>();

dto.PrintDump();

You can’t have a property name that’s a number so that needs to be a Dictionary, everything else can be a typed DTO.

That is awesome. Thank you very much.