Giter VIP home page Giter VIP logo

nancy.serialization.jsonnet's Introduction

Implementations of the ISerialization and IBodyDeserializer interfaces, based on Json.NET, for Nancy

Usage

Start of by installing the Nancy.Serialization.JsonNet nuget

When Nancy detects that the JsonNetSerializer and JsonNetBodyDeserializer types are available in the AppDomain, of your application, it will assume you want to use them, rather than the default ones.

Customization

If you want to customize the behavior of Json.NET, you can provide your own implementation of the JsonSerializer type. For example, the following implementation configures Json.NET to use camel-casing and to indent the output

public class CustomJsonSerializer : JsonSerializer
{
    public CustomJsonSerializer()
    {
        this.ContractResolver = new CamelCasePropertyNamesContractResolver();
        this.Formatting = Formatting.Indented;
    }
}

In order for Nancy to know that you want to use the new configuration, you need to register it in your bootstrapper. Here is an example of how you would do that using the DefaultNancyBootstrapper

public class Bootstrapper : DefaultNancyBootstrapper
{
    protected override void ConfigureApplicationContainer(TinyIoCContainer container)
    {
        base.ConfigureApplicationContainer(container);

        container.Register<JsonSerializer, CustomJsonSerializer>();
    }
}

Code of Conduct

This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behavior in our community. For more information see the .NET Foundation Code of Conduct.

Contribution License Agreement

Contributing to Nancy requires you to sign a contribution license agreement (CLA) for anything other than a trivial change. By signing the contribution license agreement, the community is free to use your contribution to .NET Foundation projects.

.NET Foundation

This project is supported by the .NET Foundation.

Copyright

Copyright © 2010 Andreas Håkansson, Steven Robbins and contributors

License

Nancy.Serialization.JsonNet is licensed under MIT. Refer to license.txt for more information.

nancy.serialization.jsonnet's People

Contributors

cemremengu avatar clempi avatar codeprogression avatar emilcardell avatar grumpydev avatar jchannon avatar jskimming avatar khellang avatar phillip-haydon avatar purekrome avatar rasmus-beck avatar sphiecoh avatar thecodejunkie avatar vbfox avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nancy.serialization.jsonnet's Issues

Wrong order of serializers on some machines

I 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.

v2.0.0 to use Json.NET v9?

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!

v. 0.23.0.0 references wrong Json.NET assembly

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.

dotPeek output

Custom serializer doesn't run

    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?

Support for dotnet core?

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.

No Nancy.Serialization.JsonNet v2.0.0 NuGet package

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

Nancy not picking up my custom JsonSerializer

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.

Create default JsonSerializer

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.

Enum mapping goes wrong

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).

Reset Body Stream position

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.

Exception when using Nancy.Serialization.JsonNet after upgrading to Nancy 2.0.0

Description

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.WhereEnumerableIterator1.MoveNext()
at System.Linq.Buffer1..ctor(IEnumerable1 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.ConcurrentDictionary2.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.NancyBootstrapperBase1.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)

Steps to Reproduce

Simply launch nancy with the json.net serializer.

System Configuration

.NET 4.7

  • Nancy version: 2.0.0
  • Nancy host
    • ASP.NET
    • OWIN
    • Self-Hosted
    • Other:
  • Other Nancy packages and versions:
  • Environment (Operating system, version and so on):
  • .NET Framework version:
  • Additional information:

Failing to automatically register dependencies

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"}

passing JsonNetBodyDeserializer to result.Body.Deserialize throws ArgumentNullException

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?

JsonSerializerSettings per request?

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?

Lower-case keys after update to Nancy 0.22

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?

FormatterExtensions.jsonSerializer keeps wrong serializer with Diagnostics

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.

Nancy.Serialization.JsonNet 0.22.2 for .NET 4.0 has a dependency on a .NET 4.5 JSON.NET dll

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.

Nancy.Serialization.JsonNet.dll not loading in Production

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!

Fresh clone does not build out-of-the-box in Visual Studio 2017

Prerequisites

  • I have written a descriptive issue title
  • I have verified that I am running the latest version of Nancy
  • I have verified if the problem exist in both DEBUG and RELEASE mode
  • I have searched open and closed issues to ensure it has not already been reported

Description

The 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.

Steps to Reproduce

  1. Clone Nancy.Serialization.JsonNet
  2. git submodule update --init
  3. Load Nancy.Serialization.JsonNet.sln in Visual Studio 2017
  4. Build

System Configuration

  • Nancy version: master
  • Other Nancy packages and versions: master of Nancy.Serialization.JsonNet
  • Environment (Operating system, version and so on): Windows 10
  • .NET Framework version: Full-updated Visual Studio 2017 Preview with all modern .NET Framework SDKs and the .NET Core SDK installed
  • Additional information: Latest Windows 10 SDK installed (build 16299)

Unable to deserialize to Newtonsoft.Json.Linq.JToken

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?

Must register ISerializer in container

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.

how to convert the null to '' ,when using Response.AsJson(msg);

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"
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.