It should go a little something like this... But! this is where I got stuck... I have no idea how to do the custom ContractResolver part!
var settings = new JsonSerializerSettings
{
ContractResolver = new MyContractResolver() // HEP ME!
};
var json = ... // from above
var foo = JsonConvert.DeserializeObject<MyClass>(json, settings);
foo.DoSomething();
Can anybody shed any light* on this?
...or it could be that I'm taking the wrong approach in the first place. I'm open to alternative suggestions.
//register your type
public class LighInjectComposer : IUserComposer
{
public void Compose(Composition composition)
{
composition.Register(typeof(MyClass));
}
}
How to deserialize JSON with LightInject dependency injection?
Hey there Umbraco 8 fans!
I'm struggling to figure out how to do dependency injection (LightInject) when deserializing JSON to a C# class object.
My use-case is that I have a JSON string, which I need to deserialize to an object that I can make method calls - and use Umbraco service APIs.
Here's what I have so far...
JSON
C# Class
At this point, I started reading up about JSON.NET
ContractResolvers
, and how to configure them for Dependency Injection...https://www.newtonsoft.com/json/help/html/DeserializeWithDependencyInjection.htm
It should go a little something like this... But! this is where I got stuck... I have no idea how to do the custom
ContractResolver
part!Can anybody shed any light* on this?
...or it could be that I'm taking the wrong approach in the first place. I'm open to alternative suggestions.
Cheers,
- Lee
Hi Lee,
This is not going to reply to your question about LightInject but, can't you use the Current object to get the Umbraco services instead using DI?
That's at least what the docs recommend: https://our.umbraco.com/documentation/Getting-Started/Code/Debugging/Logging/#writing-to-the-log
EDIT
Are you happy with something like this?
Then use this :
Cool, thanks for the suggestion Mario.
I should have mentioned that I'm already using
Current.Logger
in my class method, oops.Thanks for the code snippet, appreciated. I wasn't aware of the
PopulateObject
method, nice! I'll give it a try.Cheers,
- Lee
is working on a reply...