nancyfx / nancy.serialization.jsonnet Goto Github PK
View Code? Open in Web Editor NEWNewtonSoft.Json serializer for Nancy
License: MIT License
NewtonSoft.Json serializer for Nancy
License: MIT License
DEBUG
and RELEASE
modeThe how_to_build.txt
file starts off with this sentence:
NOTE These instructions are only for building with Cake - if you just want to build the project manually you can do so just by loading the solution into Visual Studio 2015 and pressing build :-)
I do not have Visual Studio 2015, but I do have Visual Studio 2017. The project loads fine in Visual Studio 2017 (once a git submodule update --init
has been run -- might be worth mentioning this in how_to_build.txt
?), but attempting to build results in hundreds of errors like these:
1>Json\SimpleJson.cs(58,14,58,18): error CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)
1>Json\SimpleJson.cs(63,14,63,21): error CS0234: The type or namespace name 'Dynamic' does not exist in the namespace 'System' (are you missing an assembly reference?)
1>AppDomainAssemblyCatalog.cs(7,18,7,22): error CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)
1>AsyncNamedPipelineBase.cs(5,18,5,22): error CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)
...
1>DynamicDictionary.cs(123,16,123,23): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference?
1>DynamicDictionary.cs(203,37,203,44): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference?
1>DynamicDictionary.cs(212,46,212,53): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference?
1>DynamicDictionary.cs(244,49,244,56): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference?
...
1>DynamicDictionary.cs(165,30,165,36): error CS0115: 'DynamicDictionary.Equals(object)': no suitable method found to override
1>DynamicDictionary.cs(193,29,193,40): error CS0115: 'DynamicDictionary.GetHashCode()': no suitable method found to override
1>DynamicDictionary.cs(15,84,15,102): error CS0535: 'DynamicDictionary' does not implement interface member 'IHideObjectMembers.GetType()'
1>DynamicDictionary.cs(15,84,15,102): error CS0535: 'DynamicDictionary' does not implement interface member 'IHideObjectMembers.ToString()'
There are 342 such errors, almost all of them represented in the above sample. They are generated by the build of the main Nancy.csproj project, and the failure of that project to build cascades to the other projects in the solution, as there is no Nancy.dll build output for them to reference.
git submodule update --init
master
master
of Nancy.Serialization.JsonNetI have .NET 4.6.1, Nancy 1.4.3, Nancy.Serialization.JsonNet 1.4.1 and compile my project by VS 2015 C# 6.0. I use FormatterExtensions.AsJson
to format the response. On some machines (I would call them MachinesA) the formatter.Serializers
is
Nancy.Responses.DefaultXmlSerializer,Nancy.Serialization.JsonNet.JsonNetSerializer,Nancy.Responses.DefaultJsonSerializer
while on the other machines (MachinesB) the order is:
Nancy.Responses.DefaultXmlSerializer,Nancy.Responses.DefaultJsonSerializer,Nancy.Serialization.JsonNet.JsonNetSerializer
So the response is formatted by DefaultJsonSerializer
and not JsonNetSerializer
. I cannot find, what's the difference between MachinesA and MachinesB. They all have .NET 4.6.1 installed, they have various OS (Win 10, Win 7, ...). My application is always the same - just copy of the folder.
The readme.md describes the mechanism for customising serialization by creating a custom serializer.
Since the release of Json.NET 5.0 a built in mechanism is provided to globally customize serialization.
The JsonNetSerializer and JsonNetBodyDeserializer could both be updated to make use of this mechanism with the following change:
this.serializer = JsonSerializer.CreateDefault();
If you agree this is worthwhile I'll happy submit a pull request.
public sealed class CustomJsonSerializer : JsonSerializer
{
public CustomJsonSerializer()
{
ContractResolver = new CamelCasePropertyNamesContractResolver();
NullValueHandling = NullValueHandling.Ignore;
DefaultValueHandling = DefaultValueHandling.Ignore;
}
}
public class CustomApiBootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
{
base.ConfigureRequestContainer(container, context);
container.Register<JsonSerializer, CustomJsonSerializer>();
}
}
The CustomJsonSerializer
constructor never executes. The JSON response still has null properties.
{
"data": {
"application": "myApp",
"version": "1.0",
"links": {
"self": {
"href": "/api"
}
}
},
"message": null,
"status": "success"
}
What's missing?
I've noticed that, when using this.Bind<>()
, I lose my enum values and some of them goes to default (0). In other cases I've noticed that the enum values change from the original request when i use this.Body<>()
. For example I have enum "Dog = 1, Cat = 2, Horse = 3", my original request holds an object with enum values "1, 3" but when I bind, they turn to "3, 3" (Horse, horse).
Since this patch in Nancy : NancyFx/Nancy#1613 the compilation of this project is broken.
Regards,
The latest build has just been upgraded to Json.NET Version 6.0.3, but is seems that the released assembly has not been compiled with the new version before being released.
Looking at the assembly using dotPeek, you can see that it still references the old version of Json.NET, but the packages.json file is correct.
Compiling the project locally gets the correct assembly reference.
I followed the readme.md
instructions after creating my custom JsonSerializer
in order to register it. But it wasn't picked up. I had to add the following lines to make it work:
container.Register<ISerializer, JsonNetSerializer>();
container.Register<IBodyDeserializer, JsonNetBodyDeserializer>();
Is the documentation incomplete/inaccurate or have I missed something? It clearly states that Nancy should detect JsonNetSerializer
and JsonNetBodyDeserializer
but it fails to do so.
I'm attempting to change the serializer settings per request. Right now I'm trying to register a custom JsonSerializer in ConfgureRequestContainer based on header values but this doesn't seem to work. The construct is never called. If I register in ConfigureApplicationContainer, it works fine but I can't query the header. I'm assuming the composition happens before this.
Anyone have any ideas?
I've got a very weird situation.
Obviously on my development machine Nancy.Serialization.JsonNet loads properly in my project.
However, in production Nancy.Serialization.JsonNet does not load.
I can confirm the assemblies loaded using Sysinternals Process Explorer, and my initial review of the FusionLogs in production do not indicate a problem. However, I do have a "Total # of load failures" count of 1 in production, and 0 in development.
I'm not expecting a solution to this, at the moment; just putting something here for the google gods for the other poor souls who have to spend 5 days tracking this down.
I've tried upgrading the project to .NET 4.6, down to 4.0, nothing.
I think I'm going to have to manually return JSON strings, and manually handle them in my client library for now. Bummer!
Method 'CanDeserialize' in type 'Nancy.Serialization.JsonNet.JsonNetBodyDeserializer' from assembly 'Nancy.Serialization.JsonNet, Version=1.4.1.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
at System.Reflection.RuntimeAssembly.GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes)
at System.Reflection.RuntimeAssembly.GetExportedTypes()
at Nancy.Extensions.AssemblyExtensions.SafeGetExportedTypes(Assembly assembly)
at Nancy.DefaultTypeCatalog.<>c.b__4_0(Assembly assembly)
at System.Linq.Enumerable.d__172.MoveNext() at System.Linq.Enumerable.WhereEnumerableIterator
1.MoveNext()
at System.Linq.Buffer1..ctor(IEnumerable
1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable1 source) at Nancy.DefaultTypeCatalog.GetTypesAssignableTo(Type type) at Nancy.DefaultTypeCatalog.<>c__DisplayClass3_0.<GetTypesAssignableTo>b__0(Type t) at System.Collections.Concurrent.ConcurrentDictionary
2.GetOrAdd(TKey key, Func2 valueFactory) at Nancy.DefaultTypeCatalog.GetTypesAssignableTo(Type type, TypeResolveStrategy strategy) at Nancy.TypeCatalogExtensions.GetTypesAssignableTo[TType](ITypeCatalog typeCatalog) at Nancy.Bootstrapper.NancyInternalConfiguration.<>c.<get_Default>b__1_0(ITypeCatalog typeCatalog) at Nancy.Bootstrapper.NancyBootstrapperBase
1.GetInitializedInternalConfiguration()
at Nancy.Bootstrapper.NancyBootstrapperBase`1.Initialise()
at Nancy.Hosting.Self.NancyHost..ctor(INancyBootstrapper bootstrapper, HostConfiguration configuration, Uri[] baseUris)
at Nancy.Hosting.Self.NancyHost..ctor(INancyBootstrapper bootstrapper, Uri[] baseUris)
Simply launch nancy with the json.net serializer.
.NET 4.7
I have updated Nancy from 0.21 to 0.22 and noticed a change that broke my server. All the JSON keys in JSON response (Response.AsJSON) changed to lower case. Is this a known issue or a bug? If it is not a bug, how to make it behave like before?
Hello,
The NancyFx v2 official release is available in Nuget since april 2019 but the Nancy.Serialization.JsonNet is not amongst them. Is there a reason for this?
P.S.: for the moment I am using a mix of v2.0.0 and v2.0.0-clinteastwood
I'm trying to use the JsonNet package but it is not working with self hosted Nancy. I think I'm doing everything as needed, installing the package from Visual Studio will result in versions
<packages>
<package id="Nancy" version="1.4.3" targetFramework="net45" />
<package id="Nancy.Hosting.Self" version="1.4.1" targetFramework="net45" />
<package id="Nancy.Serialization.JsonNet" version="1.4.1" targetFramework="net45" />
<package id="Newtonsoft.Json" version="8.0.2" targetFramework="net45" />
</packages>
Code is very basic
static void Main(string[] args)
{
using (var host = new NancyHost(new Uri("http://localhost:1234"), new NancyBootstrapper()))
{
host.Start();
Console.ReadLine();
host.Stop();
}
}
For running nancy and small bootstrapper and custom serializer
public class NancyBootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
container.Register<JsonSerializer, CustomJsonSerializer>();
}
}
public class CustomJsonSerializer : JsonSerializer
{
public CustomJsonSerializer()
{
ContractResolver = new CamelCasePropertyNamesContractResolver();
Formatting = Formatting.Indented;
}
}
This is the exception message
An unhandled exception of type 'System.InvalidOperationException' occurred in Nancy.dll
Additional information: Something went wrong when trying to satisfy one of the dependencies during composition, make sure that you've registered all new dependencies in the container and inspect the innerexception for more details.
And further Innerexception
{"Unable to resolve type: Nancy.NancyEngine"}
{"Unable to resolve type: Nancy.Routing.DefaultRequestDispatcher"}
{"Unable to resolve type: Nancy.Routing.DefaultRouteResolver"}
{"Unable to resolve type: Nancy.Routing.DefaultNancyModuleBuilder"}
{"Unable to resolve type: Nancy.DefaultResponseFormatterFactory"}
{"Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)":"Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed"}
yo aspnet nancy Test
cd Test
dotnet add package Nancy.Serialization.JsonNet
error: Package Nancy.Serialization.JsonNet 1.4.1 is not compatible with netcoreapp1.0 (.NETCoreApp,Version=v1.0). Package Nancy.Serialization.JsonNet 1.4.1 supports: net40 (.NETFramework,Version=v4.0)
error: One or more packages are incompatible with .NETCoreApp,Version=v1.0.
error: Package 'Nancy.Serialization.JsonNet' is incompatible with 'all' frameworks in project '/home/chris/git/NANCY/Test/Test.csproj'.
And I'd love it to be compatible with netcoreapp1.1
as well even. I don't know how to go about fixing this or else I'd gladly make the PR myself -- feel free to just point me in the right direction if that will get this resolved faster.
Hi, a small issue,
In order to use Nancy.Serialization.JsonNet with Nancy 1.4.3, I had to manually register the ISerializer
and the CustomJsonSerializer
, otherwise the custom serializer would not be used.
container.Register<ISerializer, JsonNetSerializer>();
container.Register<JsonSerializer, CustomJsonSerializer>();
The home page doc states that we only need to register the customer serializer.
Thanks.
I have Nancy 1.4.3, Nancy.Serialization.JsonNet 1.4.1. When start my app with Nancy diagnostics and go first to the http://localhost:8080/_Nancy/interactive#Testing%20Diagnostic%20Provider
and then run my request, the request is formatted by the DefaultJsonSerializer
and not JsonNetSerializer
since the FormatterExtensions.jsonSerializer
keeps the DefaultJsonSerializer
from the first request.
I guess both jsonSerializer
and xmlSerializer
fields should be removed.
Hi guys,
Do you have any intentions to update v2 to use netcoreapp1.0 and Json.Net 9.0.1?
I had to add net452 as a dependency to my project just because of Nancy.Serialization.JsonNet and it conflicted with Json.Net 9 package I'm using...
Thank you!
I use the Nancy.Serialization.JsonNet and register the JsonSerializer
:
container.Register<JsonSerializer, CustomJsonSerializer>();
And define the class
public class CustomJsonSerializer : JsonSerializer
{
public CustomJsonSerializer()
{
this.Formatting = Formatting.Indented;
this.DateFormatString = "yyyy-MM-dd HH:mm:ss";
this.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
this.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
this.NullValueHandling = NullValueHandling.Include;
}
}
I return a JSON object using return Response.AsJson(msg)
in the interface, but the result contain null
values. I want to know how to convert the null
value to ''
value, thanks!
Such as:
{
"action": "GET /webbase/GetTypeList/2/10",
"error": "",
"result": [
{
"ID": 27,
"CType": "2",
"TypeName": "in",
"TopID": 0,
"LinkUrl": **null**
},
{
"ID": 28,
"CType": "2",
"TypeName": "out",
"TopID": 0,
"LinkUrl": **null**
}
],
"result2": null,
"result3": null,
"result4": null,
"result1": null,
"total": 0,
"ResultType": "json"
}
In a test I am writing, I have some assertions on the deserialized JSON that I get back from my API. The deserialization and assert looks like this:
var output = result.Body.Deserialize<MyOutput>(new JsonNetBodyDeserializer());
Assert.That( output... );
Unfortunately, I never get to the assert. Instead, I get an ArgumentNullException from System.Linq.Enumerable.
Here's how that happens. When result.Body.Deserialize() executes, it has the following code in it:
var bindingContext = new BindingContext { DestinationType = typeof(TModel) };
return (TModel)bodyDeserializer.Deserialize(bodyWrapper.ContentType, bodyWrapper.AsStream(), bindingContext);
Notice in particular the only property defined in bindingContext is DestinationType. In particular the ValidModelBindingMembers property is null.
Now, when the JsonNetBodyDeserializer Deserialize() method is executed, there is code in there that looks like this:
if (properties.Concat(fields).Except(context.ValidModelBindingMembers).Any()){...}
In other words, the argument to Except() is null, which immediately causes Except() to throw an exception.
My conclusion is that JsonNetBodyDeserializer is guarenteed never to work in this scenario.
Is this a bug, or am I somehow misusing the class in the first place?
Are there plans to support the netcoreapp1.0 target? It seems that even with 2.0.0-barneyrubble, the only supported platform is .NET Framework 4.5.2.
Hi,
given the following dto
public class Dto
{
public Guid Id { get; set; }
public string Name { get; set; }
}
this code work as expected, receiving application/json
body and responding with application/json
Post["/echo"] = arg => this.Bind<Dto>();
the same request return an empty json ({}
) with this implementation
Post["/echo"] = arg => this.Bind<JObject>();
What's wrong with this endpoint? Isn't deserialization to JToken
working?
It would be good to add support for .NET Standard. Any plans for this?
Please reset the body position in the Deserialize method so multiple calls to this.Bind can be performed.
Please see line 37 in Nancy.ModelBinding JsonBodyDeserializer.cs which handles this.
Hi
I have a .NET 4.0 web api project with NancyFX and your serialization plugin. This project stops building as soon as I reference the JsonNetSerializer class directly with the error: Composition\Bootstrapper.cs(5,13): error CS0234: The type or namespace name 'Serialization' does not exist in the namespace 'Nancy' (are you missing an assembly reference?)
Further investigation in our build.log file yields this warning:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(1605,5): warning MSB3275: The primary reference "Nancy.Serialization.JsonNet" could not be resolved because it has an indirect dependency on the assembly "Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" which was built against the ".NETFramework,Version=v4.5" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v4.0".
I checked the .dll in your NuGet package with DotPeek and even though it clearly states it's a .NET 4.0 dll, if I download your master.zip, swap out the JSON.NET reference to one with version 6.0.2 (also .NET 4.0), repack your package and use that one, everything works again.
If I replicate the project as a .NET 4.5 project, everything also works.
Thanks in advance for the help.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.