Serializing .net class with decimal (5,2) #206
-
Hello, I just started to use the Chr.Avro library The default schemabuilder seems to always use precision (29, 14) and scale for Avro decimal logical type When I create the schema for my .Net class, I would like to be able to specify that all decimal should be with precision and scale (5,2). How could I do that? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 2 replies
-
To override that default, you can create a custom schema builder case that sets a custom precision and scale: using System;
using Chr.Avro.Abstract;
public class CustomDecimalSchemaBuilderCase : SchemaBuilderCase, ISchemaBuilderCase
{
public virtual SchemaBuilderCaseResult BuildSchema(Type type, SchemaBuilderContext context)
{
if (type == typeof(decimal))
{
var decimalSchema = new BytesSchema
{
LogicalType = new DecimalLogicalType(5, 2),
};
try
{
context.Schemas.Add(type, decimalSchema);
}
catch (ArgumentException exception)
{
throw new InvalidOperationException($"A schema for {type} already exists on the schema builder context.", exception);
}
return SchemaBuilderCaseResult.FromSchema(decimalSchema);
}
else
{
return SchemaBuilderCaseResult.FromException(new UnsupportedTypeException(type, $"{nameof(CustomDecimalSchemaBuilderCase)} can only be applied to the {typeof(decimal)} type."));
}
}
} and then create a custom schema builder that uses it: var schemaBuilder = new SchemaBuilder(
SchemaBuilder.CreateDefaultCaseBuilders()
.Prepend(builder => new CustomDecimalSchemaBuilderCase(builder)));
var schema = schemaBuilder.BuildSchema<decimal>(); |
Beta Was this translation helpful? Give feedback.
-
thanks a lot !! I have another question though ... how to ensure that the order in the json schema matches the order of my .net object/class? |
Beta Was this translation helpful? Give feedback.
-
No I was still on 8.0.2 |
Beta Was this translation helpful? Give feedback.
-
As of 9.0.0, you can use the For earlier versions, or to change the default precision and scale for all generated decimal schemas, see this previous answer. |
Beta Was this translation helpful? Give feedback.
As of 9.0.0, you can use the
[Range]
attribute to override decimal precision and scale for a field or property. See the release notes for details.For earlier versions, or to change the default precision and scale for all generated decimal schemas, see this previous answer.