views:

878

answers:

4

I'm wondering if there is a tool out there that can take in a JSON string, analyze it, and generate a C# class file that can then be used to deserialize the json string into a C# object of that class.

I'm looking for something similar to a code generator of sorts, but the input would be a JSON string, instead of a database table/view/whatever, and the output would be your typical C# class file.

Anyone have any suggestions?

+2  A: 

Nothing that I know of, but it shouldn't be that hard using one of the code generator out there (MyGeneration / CodeSmith / CodeBreeze).

The trick is that Javascript is rather loosely typed, so JSON doesn't always have enough information to decide what's the base C# data type to make a property. Also, one of the advantages of JSON is that you can freely add new properties, or leave out properties not needed for that message. So, for the message used to generate the code has all the properties that it is going to use.

James Curran
Thanks James. Good points. I'm trying to consume a JSON service which I don't control, so I'm really only interested in a particular set of data points. I'm really just trying to get the bulk of the work done, and once I get it into a C# class I can polish it up. Can you use any of the generators you've described to target a JSON string as an input instead of a database?
Joseph
Sure --- They all include a assembly which allows access to a database's schema, but if you want to get you input for somewhere else, that's fine. They are all template based, so you'll need a new template.
James Curran
A: 

How about the DataContractJsonSerializer in .NET 3.5 ? It's a specialized version of the DataContractSerializer and should work just fine serializing objects to JSON, and deserializing JSON into objects.

Marc

marc_s
@marc_s That takes care of serializing/deserializing the JSON object to a C# class, but it doesn't help me actually define what the C# class should be. What I have is a JSON object coming to me through a JSON service. I don't have a C# class yet. I'd like to have a tool that could take the JSON object and generate a class that I could use to deserialize it into. Does that make sense?
Joseph
AH, ok, you want to deserialize to an unknown class .... hmm.... tricky......
marc_s
A: 

Did you ever create a template to generate that C# class? I would be very interested in it. Thanks.

Charlie

Charlie
Should be a comment, not an answer
phsr