Contentful.NET icon indicating copy to clipboard operation
Contentful.NET copied to clipboard

Can I create a DataModel object from a detached JSON string?

Open deanebarker opened this issue 9 years ago • 3 comments

Is it possible to create one of your DataModel objects from a JSON string?

I wrote a webhook server for Contentful. Each webhook request sends an entire object as its request body in JSON. I'm looking for a way to get an object representation of this.

Using that JSON string, could I create one of your DataModel objects?

deanebarker avatar Sep 03 '16 10:09 deanebarker

You should be able to do this. Contentful.NET uses JSON.NET to deserialize the response from the REST API to DataModel objects, so if you use the same library it should work fine.

ryan-codingintrigue avatar Sep 05 '16 08:09 ryan-codingintrigue

Do I do it manually, or can I just pass the string somewhere? I really don't want to re-implement the string-to-object logic as I don't think that would do either library any favors.

deanebarker avatar Sep 05 '16 09:09 deanebarker

The method used by Contentful.NET is internal so you won't be able to call it directly (it requires a HttpResponseResult anyway, so probably won't be of much use to you).

The simplest method would be JsonConvert.DeserializeObject:

var yourObject = JsonConvert.DeserializeObject<T>(yourJsonString);

Where T is any implementation of IContentfulItem - which covers all of the top-level DataModels.

ryan-codingintrigue avatar Sep 05 '16 11:09 ryan-codingintrigue