ConnectEverything / nats-by-example

Collection of runnable, reference examples using NATS (https://nats.io)
https://natsbyexample.com
152 stars 37 forks source link

JetStream Publish Serialization error #192

Closed alberk8 closed 1 month ago

alberk8 commented 5 months ago

I have the following code with error Can't Serialize on the await jsContext.PublishAsync<Person>("data.person", data: person); . What am I doing wrong here?

Environment NATS server 2.10.11 with JetStream enabled .Net 8.0 C# nuget: NATS.Client.JetStream 2.1.2

namespace ConsoleNatsPublisher
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello, World!");

            var opt = new NatsOpts
            {
                Url = "nats://127.0.0.1:4222",
                SerializerRegistry = NatsDefaultSerializerRegistry.Default,
                Name = "Nats_Connect"
            };

            var connect = new NatsConnection(opt);

            var jsContext = new NatsJSContext(connect) ;

            var stream = await jsContext.CreateStreamAsync(new StreamConfig("EVENTS", new[] { "data.>" }));

            var person = new Person { Name = "Nats", Address = "123 Address" };

            await jsContext.PublishAsync<Person>("data.person", data: person);

            Console.WriteLine("Done");
            Console.ReadLine();
        }

        public class Person
        {
            public string Name { get; set; } = string.Empty;
            public string Address { get; set; } = string.Empty;
        }
    }
}
Jarema commented 5 months ago

@scottf might know the answer :)

alberk8 commented 5 months ago

@Jarema Thanks for looking into this. I think I might have found the answer.
Adding more info in the Intellisense would be very helpful.

Install the nuget NATS.Client.Serializers.Json

using NATS.Client.Serializers.Json;
 var opt = new NatsOpts
 {
     Url = "nats://127.0.0.1:4222",
     SerializerRegistry = NatsJsonSerializerRegistry.Default,
     Name = "Nats_Connect"
 };
scottf commented 2 months ago

@alberk8 Can I close this or is there something that might need to be added to an example? If there is, you are welcome to contribute something and I'll help you through the PR. It also might make sense to add something directly to the client repo.

scottf commented 1 month ago

@alberk8 Closing this. If you have more questions please visit the .NET V2 CLient repo and post a discussion or issue.