简体   繁体   中英

Generating data to match JSON schema with JSON.NET

I'm sort of a beginner with Json.NET. I've gotten pretty good at serializing and deserializing typical objects using JsonConvert, but not much more than that. So this might be a stupid question.

My program receives a JSON schema from a REST server. I use this schema to generate the UI where the user can fill in data. Then I need to package up the user data and send it back to the REST server. This data must match the original schema. I haven't quite figured out how to serialize my data into a format that would be considered valid by the schema I originally received.

Thanks in advance, and apologies if this is a dumb question.

Update :

The schema could change at any time and I'd need to be able to handle that on the fly, so a concrete class implementation is out of the question.

After more digging and talking to the guy running the REST server, apparently I was making this way more difficult than it needed to be.

In the end, all I needed was a dictionary of key/value pairs, the key being the property name and the value being some data of the type specified in the schema. Luckily, Json.NET converts those into JSON perfectly.

If the schema could change and you don't want to modify the class and compile the code every time it does you can use dynamic/ExpandoObject .

Serialization example:

dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);

Deserialization example:

dynamic foo = JObject.Parse(jsonText);
string bar = foo.Bar; // bar = "something"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM