is there a way to populate an existing object from json using json.net based upon an interface - json.net

Looking for a way to do something like the following:
NewtonSoft.Json.JsonConvert.Populate<IMyContract>(jsonStr, currentObj);
where the json.net engine would only attempt to populate the properties that are identified in the IMyContract.
Any suggestions?

Maybe u can use
PopulateObject(String, Object, JsonSerializerSettings)
And use your own JsonSerializerSettings. See: http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_JsonSerializerSettings.htm
Try to use one of the delegates to restrict the properties that are set yourself. That can be based on an Interface, using reflection.
I don't know any other way. If you don't get it with the JsonSerializerSettings you can always write your own PopulateObject method using the Json framework.

Related

Use Json.Net for input binding of Azure EventGridEvent

I currently use Json.Net throughout my project and it works like a charm. Unfortunately, the input binding for Azure Functions use System.Text.Json to deserialize the EventGrid event json and bind it toEventGridEvent object from the Azure.Messaging.EventGrid 4.0.0.-beta.4 library
have a look here: https://github.com/Azure/azure-functions-host/issues/5469
This causes massive problems as all my custom JsonConverters that i have do not work at all which leads to incorrectly deserialized objects. Changing from Newtonsoft.Json to System.Text.Json is a massive amount of rework and i would absolutely like to avoid that, if i can.
Is there a way to force the input bindings to use Json.Net instead of System.Text.Jsoneither via DI in FunctionssStartup.Configure() or otherwise?

Something akin to "Sparse Fieldsets" in .NET

I'm trying to find the vocabulary to describe what I want and if it exists.
I have a table that shows a few data points from large objects. Loading the entire objects just for the table is very slow. Is there a way to only pass to the front the few properties I want without having to define a new object?
I found something called Sparse Fieldsets in JSON API, and I'm wondering if something like this exists for .NET under another name.
Update:
Talking to another coder, I realize it probably makes more sense to implement something like this between the backend and the database and make a specific call for this table. I still need to work out if I need to create a new object to support this. I think it'd still be faster if I just kept the same object but nulled out all of the connecting objects that I don't need for the table. But maybe that's considered bad practice? Also we're using Entity Framework for what it's worth.
Update 2:
I just created a new query without all of the .Include() and works well enough for what I need:
_dataContext.ApplePie
.Include(f => f.Apples).ThenInclude(f => f.Apple)
.Include(f => f.Sugars).ThenInclude(f => f.MolecularStructure)
.Include(f => f.Recipe)
Maybe you are looking for Anonymous Types?
For example, if you had a typed object with three properties, but you only wanted to operate on two:
var threePropThing = new ThreePropertyThing { Id = 1, Message = "test", ExtraProperty = "ex" };
var myAnonThing = new { Id = threePropThing.Id, Message = threePropThing.Message };
Best practice would be to not pass this anonymous object around. But, if you really needed to, you could return it as type object.
Typically, when passing data around in c#, you want to have it typed.
C# is a strongly-typed language and I would say that it is unusual for C# to support scenarios, when object definition (properties) are not known in advance, like in JSON API "fields" parameter case. Implementing this would imply using reflection to filter the properties, which is usually slow and error-prone.
When implementing C# web-services, people usually create one DTO response model per each request.
If your table has fixed set of fields, I would personally recommend to create a DTO class containing only the fields which are required for your table, and then create a method which returns this response for your specific request. While it doesn't align with "without having to define a new object" in the question, it makes the intention clear and makes it really easier to maintain the API in future.
You might want to use libraries like AutoMapper to save time and avoid duplicated code of copying the values from data model to DTO, if you have many such methods.

JSON + SOAP - Is DataContract necessary?

Here's my problem.
I'm using SOAP to retrieve information from a third-party web service.
Response time is too high, so I was planning on using JSON instead, at least in a couple of methods.
For this I'm using DataContractJsonSerializer, but I seem to be having some trouble.
For example, in SOAP there's a method called getAvailablePublic with returns an object of type getAvailablePublicResponse.
There's an equivalent for this method in JSON, which also returns a an object of type getAvailablePublicResponse.
In order to deserialize the information I needed to create a couple of data contracts, and here are my concerns:
Do I really need to create a DataContract? Why can't I use getAvailablePublicResponse object from asmx?
The problem is that if I create a DataContract, I need to use a different name other than getAvailablePublicResponse, as I would have two objects with the same name (the one created by me, and the one from SOAP), and this would require making several changes in my solution.
Hope this makes sense.
Thanks.
Can you post your client code that is making the call to the web service? I don't know what you are using now, but I'm a fan of RestSharp for making remote calls and serializing JSON to C# classes. Something like this:
RestClient client = new RestClient("http://some.domain.com/someservice?someparam=yes");
var results = client.Execute<MyGreatDTOClass>(new RestRequest(Method.GET));

Why have a separate call to get Json?

I need to get some Json to the client side from the server and it's somewhat troublesome as almost all tutorials assume an Ajax call to a separate action to get the Json.
This led me to think that there must be some reason why it is done this way. In Asp.Net MVC we can pass a Model along with the view to get the information but we can't seem to easily pass a Json object. Instead you are supposed to make a separate call to get this information.
What if the Json info is known when the page is generated, why not generate it at the same time?
I'm sorry if I wasn't clear enough. While it's nice to hear of ways to get Json to the client, the question is actually whether there is a specific reason the Ajax call method is much more popular, like security or anything like that.
Can you put something like this into your view? (rough pseudo code, assuming using a Razor view)
< script >
var myJSON = { Field: #model.Field, Field2: #model.Field2 };
< /script >
Because you do not need both at the same time... on the first call will be to get html (the view of the data - represented by a view model), and any ajax calls will be to get the possibly updated data (json serialized view model).
No reason why you can't. You could use the javacript serializer to create a JSON string that drop on the page. You could also create an action that return the json string that you called from a script tag.
What you want if you're using KnockOut, would be the Mapping plugin that turns an ordinary JS object, like that generated above, into an observable ready for KnockOut to use. See here from info. http://knockoutjs.com/documentation/plugins-mapping.html
You can use content-negotiation by setting accept header. This is considered a best practice (and according to some RESTful).
This needs to be supported and implemented at server as well. ASP NET MVC does not make it easy to support content-negotiation and you have to implement it yourself by if-else or using ActionFilter and implementing action selector.

Determining which properties to serialize in a class that's passed over a webservice

I'm using NHibernate to administer my entities, and to have lazy loading enabled I need to make my properties return an IList<>. Problem is that .NET throws an exception as it can't serialize an interface when I'm trying to pass the entity. This makes perfect sense.
What I need to know is how I can control which fields to serialize, and which not to? My best bet so far is to work around this problem by copying the contents of IList<> into a List<> before serializing the object, but to do that I need to tell .NET that I don't want the IList<> property serialized :)
Just wanted to let you guys know that I found the answer to be the
[System.Xml.Serialization.XmlIgnore] attribute :)
MSDN has an area on Serializing Objects, but what you want is Selective Serialization. So basically, you can mark any property you don't want serialized with the attribute, [NonSerialized]. There is an example in the second link.

Resources