I am currently using C# WebAPI for our API.
I need to be able to serialise as either JSON or XML only certain properties on an object. What makes this harder is that we serialise the object back and forth for use in the data layer so I cannot just use the standard attributes to ignore when serialising.
I want to create a custom attribute (ApiPropertyAttribute) and then use a filter in the serialise to only return the properties with the new attribute. We only want to use the filter for WebAPI use only.
We don't want to create a new object and use mappers for maintenance reasons.
I have looked at media type formatters and converters but can't get them to do what I want.
Any help appreciated.
Related
I am trying to set different JsonSerializerOptions for specific controllers. Specifically, I want to set ReferenceHandler = ReferenceHandler.Preserve for those controllers only, and inherit the rest of the serializer options from some static instance.
I'm looking for a way to do this at the controller level, using System.Text.Json on ASP.NET Core 6.0.
I was able to do this for serialization using an Action Filter using this solution: https://stackoverflow.com/a/56127866/2719183, but I haven't been able to find a good solution to implement this for deserialization. For example, https://stackoverflow.com/a/66256442/2719183, does not work for me because it requires an attribute for each parameter.
How do I override an input formatter at the controller level?
There are two problems: serialization and deserialization.
Serialization. This is relatively easy, you have to create action filter and inspect action result, if it is ObjectResult then you can set custom json formatter.
Deserialization/binding. This one is tricky, you'll need custom body binder (which can be configured to use custom json formatter), custom binder provider, custom binder source and custom IControllerModelConvention to selectively override binding source on actions.
This should work for simple scenarios when you don't use other filters or middlewares etc.
I'm not attaching any code, because it will be a dozen of classes.
I'm looking for a way to validate dynamic objects. The dynamic objects are used in an internal API. I know that I can
convert to XML and use XSD for validation
convert to JSON and use Json.NET .IsValid(schema) or the Json.NET Schema package
validate each property in code like HasProperty as shown here
The XML and JSON based approaches requires serialization and deserialization and this will impact performance when used frequently. The code based validation is difficult to maintain (in particular for hierarchical objects) and can't be used easily by API consumers.
I was looking to find something similar to XSD validation but natively for dynamic objects but had no luck. I'm fine if it is limited to ExpandoObjects.
My minimum requirements:
identify missing required properties
identify properties which are not specified
allow optional properties
allow nested objects
A project I am working on is consuming Web API's returning heterogeneous JSON, I don't understand why a webservice API would need to return different object graphs, but that is what is being returned.
My questions are
Is it usual/common practice to return different object graphs by the same api? By different object graph I mean a varying complex object that might have or not have some other complex objects as properties. It would have seem reasonable if the same properties returned for every call, either having a null value or a complex object as their values, but the properties being completely omitted in the response makes it hard to have a C# class to desrialise against.
How is JSON heterogeneous (de)serialisation handled in C#? Is reflection and run time code generation preferred method for this? or using dynamic/expando object?
It makes sense for some APIs to return different objects when some fields that happen to be complex objects are omitted because they do not contain information sometimes, or an endpoint returns different objects based on different parameters. Not sure if there are other cases.
As for different JSON, you have to know a little bit about what data is returned by the API and getting at least the data you need. You can use Json.NET and deserialize to a class or to a dynamic object if you are not entirely sure what to expect or don't want to create a class for it.
I also advise to read the API documentation, or do some sort of (boundary?) testing with the parameters to figure out what data to expect.
I'm trying to serialize an array of objects into JSON in C#. By array I mean something like Object[] (not Array<Object>), I'm using a JsonMediaTypeFormatter as part of MVC (the serialization is happening automatically as part of the framework but I can override it). The output contains {"count":2,"value":[{...},{...},...]}" where the ... is the json representation of the object. I've looked around and haven't found much information about suppressing this behavior. I want the output to just be the [{...},{...},...] rather than the object with count and values properties. Does anyone know how to achieve this without manually writing the code to do the serialization?
You could consider an alternative framework like the JSON.NET framework. I don't know how much you can customize if you are using an in-built .NET object since there are public properties that are not being ignored. Not using the JSONMediaTypeFormatter much, if it allows you to ignore properties, consider overriding List or ArrayList to hide certain attributes.
I would recommend not returning an array directly as there is a security flaw that could be compromised in a client browser (if that is the consumer). See this reference to find out more.
What is a better approach to serialize custom class: using XMLSerializer or BinarryFormatter and [Serializable] attribute on class?
It's not possible to answer this, without knowing how you will use the resulting file, and the lifetime of it.
The decision is based on the fact that it is harder to "upgrade" the binary format. If your object model changes, it won't deserialise correctly. But if you've implemented a custom XML serialisation/deserialisation, then you can handle the "new" cases appropriately, and life will be good.
So decide more about how you will use it, who you are sharing information with, and what the possible changes to the model are.
FWIW, I sometimes use both types of serialisation in a given project.
That really depends on how you use the serialized class. If you want to pass it to other programs or want to easily debug it, use XML (but mind that XMLSerializer might produce non-compliant XML output, like multiple root elements).
In all other cases, you can use the binary formatter. But note that XML is more suitable if you change the class later - you can use XMLIgnore and the like to keep the XML format intact.
The decision will sometimes also be made for you based on what the serialized output will be used for - while you could expose a WebService to take a binary array that is a binary serialized item, you couldn't utilize the web service easily from anything but .Net (and the end client would probably need a reference to the type).
Using XML means that the service could be exposed to any end client regardless of the platform/environment on the end client