logo
down
shadow

Custom serializer for just one property in Json.NET, without changing the model class


Custom serializer for just one property in Json.NET, without changing the model class

By : Rohit
Date : November 27 2020, 04:01 AM
To fix this issue You can programmatically apply a JsonConverter to one or more properties in a model class without using attributes via a custom ContractResolver. Here is a dirt simple example, which applies your AllCapsConverter to the LastName property in your Person class. (If you're looking for a more robust solution, have a look at @dbc's answer. My intent here was to show the simplest example that could possibly work.)
code :
public class CustomResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty prop = base.CreateProperty(member, memberSerialization);
        if (prop.DeclaringType == typeof(Person) && prop.UnderlyingName == "LastName")
        {
            prop.Converter = new AllCapsConverter();
        }
        return prop;
    }
}
public class PersonSerializationTest
{
    [Fact]
    public void SerializePerson_LastNameCaps()
    {
        var person = new Person
        {
            FirstName = "George",
            LastName = "Washington"
        };
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new CustomResolver()
        };
        var serialized = JsonConvert.SerializeObject(person, settings);
        var expected = @"{""FirstName"":""George"",""LastName"":""WASHINGTON""}";
        Assert.Equal(expected, serialized);
    }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}


Share : facebook icon twitter icon
custom serializer for just one property in Json.NET

custom serializer for just one property in Json.NET


By : leuckss
Date : March 29 2020, 07:55 AM
This might help you Turns out I just needed to inherit from JsonConverter instead of CustomCreationConverter, and everything else I was trying to change was OK all along.
I'm still not sure if there's a way to apply the JsonConverter fluently, but there is another way to apply the JsonConverter without referencing Json.NET in your domain/core project or marking up your domain classes with references to a peripheral library:
code :
var jsonSerializer = new JsonSerializer();
jsonSerializer.Converters.Add(new DbGeographyConverter());
jsonSerializer.Serialize(jsonWriter, place);
how to get property or field name in a custom json serializer

how to get property or field name in a custom json serializer


By : Maja O.
Date : March 29 2020, 07:55 AM
it fixes the issue If you implement ContextualSerializer, this will be used to produce a "contextual" version of your serializer, i.e. one that is configured using the BeanProperty:
code :
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property)
    throws JsonMappingException;
Ruby On Rails - Active Model Serializer; Create a custom JSON serializer

Ruby On Rails - Active Model Serializer; Create a custom JSON serializer


By : Security Computer
Date : March 29 2020, 07:55 AM
I wish this help you how can I create a json with this key & value mapping? , Why do you need a serializer?
code :
users.map{|u| { "#{id}": name }.to_json
how to change property or field name in a custom json serializer

how to change property or field name in a custom json serializer


By : Ильяс Акберген
Date : March 29 2020, 07:55 AM
To fix this issue I hava a custom serializer for a field. , Take a look at this
code :
public class Response {
  private String status;
  private String error;

  @JsonProperty("p")
  @JsonSerialize(using = CustomSerializer.class)
  private Object data;

  // ...
}

public class CustomSerializer extends JsonSerializer<Object> {
  public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeObjectField(value.getClass().getName(), value);
    jgen.writeEndObject();
  }
}

public static void main(String... args) throws Exception {
  ObjectMapper mapper = new ObjectMapper();
  Response r1 = new Response("Error", "Some error", 20);
  System.out.println(mapper.writeValueAsString(r1));
  Response r2 = new Response("Error", "Some error", "some string");
  System.out.println(mapper.writeValueAsString(r2));
}
Can I use TypeConverter attribute on single property of a model for Json serializer?

Can I use TypeConverter attribute on single property of a model for Json serializer?


By : Tabias
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Checking for [TypeConverter(typeof(...))] attributes applied to members is not implemented out of the box in Json.NET. You could, however, create a custom JsonConverter that wraps an arbitrary TypeConverter, then apply that to your model using JsonConverterAttribute.
First, define the following JsonConverter:
code :
public class TypeConverterJsonConverter : JsonConverter
{
    readonly TypeConverter converter;

    public TypeConverterJsonConverter(Type typeConverterType) : this((TypeConverter)Activator.CreateInstance(typeConverterType)) { }

    public TypeConverterJsonConverter(TypeConverter converter)
    {
        if (converter == null)
            throw new ArgumentNullException();
        this.converter = converter;
    }

    public override bool CanConvert(Type objectType)
    {
        return converter.CanConvertFrom(typeof(string)) && converter.CanConvertTo(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var tokenType = reader.SkipComments().TokenType;
        if (tokenType == JsonToken.Null)
            return null;
        if (!tokenType.IsPrimitive())
            throw new JsonSerializationException(string.Format("Token {0} is not primitive.", tokenType));
        var s = (string)JToken.Load(reader);
        return converter.ConvertFrom(null, CultureInfo.InvariantCulture, s);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var s = converter.ConvertToInvariantString(value);
        writer.WriteValue(s);
    }
}

public static partial class JsonExtensions
{
    public static JsonReader SkipComments(this JsonReader reader)
    {
        while (reader.TokenType == JsonToken.Comment && reader.Read())
            ;
        return reader;
    }

    public static bool IsPrimitive(this JsonToken tokenType)
    {
        switch (tokenType)
        {
            case JsonToken.Integer:
            case JsonToken.Float:
            case JsonToken.String:
            case JsonToken.Boolean:
            case JsonToken.Undefined:
            case JsonToken.Null:
            case JsonToken.Date:
            case JsonToken.Bytes:
                return true;
            default:
                return false;
        }
    }
}
public class JsonModel
{
    [JsonConverter(typeof(TypeConverterJsonConverter), typeof(CidNumberConvertor))]
    [TypeConverter(typeof(CidNumberConvertor))]
    [JsonProperty("cid_number")]
    public Cid CidNumber;

    [JsonConverter(typeof(TypeConverterJsonConverter), typeof(CidHexaConvertor))]
    [TypeConverter(typeof(CidHexaConvertor))]
    [JsonProperty("cid_hexa")]
    public Cid CidHexa;

    [JsonProperty("cid_default")]
    public Cid CidDefault;
}
public class PropertyTypeConverterContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);

        if (property.Converter == null)
        {
            // Can more than one TypeConverterAttribute be applied to a given member?  If so,
            // what should we do?
            var attr = property.AttributeProvider.GetAttributes(typeof(TypeConverterAttribute), false)
                .OfType<TypeConverterAttribute>()
                .SingleOrDefault();
            if (attr != null)
            {
                var typeConverterType = GetTypeFromName(attr.ConverterTypeName, member.DeclaringType.Assembly);
                if (typeConverterType != null)
                {
                    var jsonConverter = new TypeConverterJsonConverter(typeConverterType);
                    if (jsonConverter.CanConvert(property.PropertyType))
                    {
                        property.Converter = jsonConverter;
                        // MemberConverter is obsolete or removed in later versions of Json.NET but
                        // MUST be set identically to Converter in earlier versions.
                        property.MemberConverter = jsonConverter;
                    }
                }
            }
        }

        return property;
    }

    static Type GetTypeFromName(string typeName, Assembly declaringAssembly)
    {
        // Adapted from https://referencesource.microsoft.com/#System/compmod/system/componentmodel/PropertyDescriptor.cs,1c1ca94869d17fff
        if (string.IsNullOrEmpty(typeName))
        {
            return null;
        }

        Type typeFromGetType = Type.GetType(typeName);

        Type typeFromComponent = null;
        if (declaringAssembly != null)
        {
            if ((typeFromGetType == null) ||
                (declaringAssembly.FullName.Equals(typeFromGetType.Assembly.FullName)))
            {
                int comma = typeName.IndexOf(',');
                if (comma != -1)
                    typeName = typeName.Substring(0, comma);
                typeFromComponent = declaringAssembly.GetType(typeName);
            }
        }

        return typeFromComponent ?? typeFromGetType;
    }
}
// Cache statically for best performance.
var resolver = new PropertyTypeConverterContractResolver();
var settings = new JsonSerializerSettings
{
    ContractResolver = resolver,
};

var json = JsonConvert.SerializeObject(root, Formatting.Indented, settings);

var root2 = JsonConvert.DeserializeObject<JsonModel>(json, settings);
Related Posts Related Posts :
  • Linq to object Multiple Where short circuit evaluation
  • WPF - Create solid layout without designer
  • View not rendering on NET Core
  • Proper way to create domain models and viewmodels in microservices
  • StaticInjectorError(AppModule)[AuthGuard] after login
  • Getting Entity Model dynamically based on TableName?
  • Customizing the Navigation Form after my form's confirmation dialog
  • CSHTML Confirm Delete prior to deleting database record
  • How to set property values for indexers using Expressions?
  • My Mandelbrot sketching program in c# isn't working
  • Best way to validate a date string in C#
  • Bot Framework v4 Bot emulator authentication bad request
  • Can I use MVC 5 remote validation to check for duplicate values, but exclude the item being edited?
  • How to get list of all databases using MongodbClient class. (C# application)
  • WPF DataGrid disable cell edit based on value
  • how to check if there are 4 or more spaces in streamread line
  • How to perform style changes on datagridview rows using rows from the underlying bindingsource?
  • How do I add a C# solution file in Jetbrains Rider?
  • Docker ASP.NET CORE 2.1 app in Visual Studio 2017. App does not start in debug mode
  • ASP.NET Core WebApi with SQL Server and EFCore 2
  • Sitefinity Widget User Control
  • MultiSelectList shows one value from the IEnumerable given to it with multiple values
  • Items in picker from a list - Xamarin Code behind
  • How can I insert/update a List<T> as member of an entity in SQLite?
  • How to "flush" ApplicationInsightsTraceListener, in a Console Application, on exit?
  • Named Pipes Between Winforms and Service Can Only Connect Once
  • Add CDATA to a Node Value in a loop
  • How to stop a timer/change system UI OnSleep Xamarin Android
  • LINQ parse xml file and get values from specific nodes
  • How do I set the time out for page load?
  • Clarification of IL generated code referenced to strings
  • EntityFrameworkCore.SQLLite and UWP Not behaving as expected
  • WPF MediaElement: Video opened twice
  • Temporary excel file with Interop library
  • Insert \u2265 into a C# string
  • Constant Enemy Damage to Player - Unity 2019.1 Beta
  • Is there a way to scan for viruses when downloading an attachment using EWS?
  • How to generify a method when T can be multiple new () Types?
  • Reading binary file data into List of Structs
  • Updating Status Strip on Form from BackgroundWorker
  • Visual Studio using GIT repository Publishing with API and Website in one Solution
  • Return Standard Deviation of column values with other column value condition LINQ
  • Grab a count of different values in object
  • c# File used by who?
  • How to parse string into an array using set number of characters in C#
  • How to sent list using CommandParameter
  • Problem with referencing ResourceDictionaries, and Styling across multiple assemblies
  • StackExchange Redis - high CPU usage on WriteAllQueues
  • Not typing the full variable name but partial name is represented by another string value
  • Linq to Entities Selecting Data with Max Date?
  • How to extract data using Ical.Net?
  • C# program crashes because listbox items change
  • Kicking a user in Discord.Net
  • C# Linq Find duplicates with multiple group by
  • How to call control on a Panel that is inside usercontrol
  • c# ReadAsJsonAsync in framework 4.5
  • Inner join two table variables and return an output cursor from an anonymous plsql block in a c# application
  • Notify consumers when all tasks have completed without blocking the thread
  • Replace "\\" with "\" in a path
  • CSS Not formatting inside repeater
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org