Tips for renaming property names during JSON serialization in asp.Net

In my MVC Web API Controller, there is a method that I have exposed:

    [HttpPost]
    public JsonResult<CustomClass> Details(RequestClass request)
    {
        var encoding = Encoding.GetEncoding("iso-8859-1");
        var settings = new Newtonsoft.Json.JsonSerializerSettings();
        return Json(_InputService.CustomClassGet(request.Id), settings, encoding);
    }

CustomClass is a complex class with multiple levels of objects from different classes. These objects are constructed in another section of the code using a mapper dependent on Newtonsoft JSON.

I recently received a request to change some property names within CustomClass (throughout the entire structure). My initial thought was to create another set of classes - one for data input and another for data output, with a converter in between. However, due to the complexity and number of classes involved, this approach would require significant effort. Additionally, the conversion process would result in double the memory usage to store two identical sets of data.

My second idea was to utilize

JsonProperty(PropertyName ="X")
to alter the generated JSON output. However, this caused issues with the input process which also relies on Newtonsoft JSON.

Next, I considered creating a custom serializer and using the

[JsonConverter(typeof(CustomCoverter))]
attribute. Unfortunately, this resulted in a global change to how CustomClass is serialized across the board, rather than allowing me to customize serialization for specific methods.

Therefore, my question is... Does anyone have any suggestions on how to selectively modify the serialization of my CustomClass for certain methods only?

Answer №1

Here is the solution that worked for me:

1) I crafted a custom Attribute and used it to mark the properties requiring name changes in the serialized Json:

[AttributeUsage(AttributeTargets.Property)]
class MyCustomJsonPropertyAttribute : Attribute
{
    public string PropertyName { get; protected set; }

    public MyCustomJsonPropertyAttribute(string propertyName)
    {
        PropertyName = propertyName;
    }
}

2) I then annotated the properties accordingly:

class MyCustomClass
{
    [MyCustomJsonProperty("RenamedProperty")]
    public string OriginalNameProperty { get; set; }
}

3) A Custom Resolver was implemented using reflection to map the property names for those decorated with MyCustomJsonPropertyAttribute:

class MyCustomResolver : DefaultContractResolver
{               
    public MyCustomResolver()
    {            
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty prop = base.CreateProperty(member, memberSerialization);

        var attr = member.GetCustomAttribute(typeof(MyCustomJsonPropertyAttribute));
        if (attr!=null)
        {
            string jsonName = ((MyCustomJsonPropertyAttribute)attr).PropertyName;
            prop.PropertyName = jsonName;
        }
        return prop;
    }

}

4) Finally, I updated the controller method like this:

    [HttpPost]
    public JsonResult<MyCustomClass> Details(RequestClass request)
    {
        var encoding = Encoding.GetEncoding("iso-8859-1");
        var settings = new Newtonsoft.Json.JsonSerializerSettings()
        {
            ContractResolver = new MyCustomResolver()
        };
        return Json(_InputService.CustomClassGet(request.Id), settings, encoding);
    }

Special thanks to dbc for guiding me in the right direction.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it recommended to utilize JSON in conjunction with jQuery and AJAX within a PHP file?

I've never had the chance to work with json before and honestly, I'm pretty clueless about how it functions. I'm looking to utilize jquery for making ajax calls to a php file. Is it recommended to use json in this scenario? I've heard t ...

Is there a way to modify data while serializing with JSON.NET?

Utilizing Newtonsoft JSON.NET 4.5r7 in a non-api MVC4 project has been my latest endeavor. In the process, I've successfully renamed "id" to DT_RowId for DataTables "mDataProp", but now desire to alter the data itself - turning, for example, 42 into ...

Completely Erase a Row from JSON

Does anyone know how to completely remove a specific line from a JSON when using a deletion method? I have a button that determines which line should be removed, but even though the correct index is passed in, the row does not get deleted entirely and just ...

Building custom components in Vue.js/NuxtJS can be a breeze when using a default design that can be easily customized through a JSON configuration

Currently, I am in the process of developing a NuxtJS website where the pages and components can either have a generic design by default or be customizable based on client specifications provided in the URL. The URL structure is as follows: http://localh ...

Sending data as POST when receiving JSON using SwiftyJSON

I've been working on an iOS app using Xcode and Swift. Currently, I am retrieving JSON data with the help of SwiftyJSON.swift along with this code: import UIKit class ViewController: UIViewController { var dict = NSDictionary() @IBOutlet ...

Steps for Adding a JSON Array into an Object in Angular

Here is a JSON Array that I have: 0: {name: "Jan", value: 12} 1: {name: "Mar", value: 14} 2: {name: "Feb", value: 11} 3: {name: "Apr", value: 10} 4: {name: "May", value: 14} 5: {name: "Jun", value ...

Deciphering the String in Restify

Consider the JSON snippet below: { "_id":"1", "Time":"03:20:22" } I am looking to modify the "Time" value by adding 2 hours, resulting in "05:20:22". However, I am facing challenges with parsing the JSON data in Restify. When I try to split the t ...

Populating datagrid columns with database information post page load

I am currently facing an issue with a web page where loading additional data from an SQL query into a datagrid is significantly slowing down the performance. Despite ensuring that all necessary database indices are in place, the query now takes 3-4 seconds ...

Outputting undefined values when processing an http post array

I seem to have encountered a major issue. Despite my efforts, I am seeing an undefined value when trying to display this JSON data. {"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [ {"sensor_serial":"SensorSerial1", "id":"11E807676E3F3 ...

Unexpected behavior with the array of objects

I am looking to structure a JSON in the following format: How can I insert multiple objects into a single array? { Data: [ {"dataType":"com.google.weight", "startDate":"2021-04-1308:00", "endDate&qu ...

The winform does not recognize the ImplicitlyWait command

I am trying to implement the following code: driver.Manage().Timeouts().ImplicitlyWait(10, TimeUnit.SECONDS); However, when I try to add it to my project, I encounter an error. error image link I have included *using OpenQA.Selenium.Support.UI; in my p ...

An unhandled SocketException occurred while constructing a C# Selenium WebDriver test

Just starting out with Selenium WebDriver and diving into the learning process. Currently following a tutorial available at A glance at the initial piece of code: static void Main(string[] args) { IWebDriver driver = new FirefoxDriver(); driver. ...

Exploring nested properties in JSON using a list of indexes in Python

Is there a method to iterate through a JSON when the indexes are listed in Python? JSON: { "id" : "abc", "Obj1": { "Obj1":{ "Name" : "123456789" } } } Traditionally, we access JSON indices like this: data[&apo ...

Tips for understanding the encoding of an NSString in UTF-8

Currently, I'm utilizing SBJSONParser for parsing a JSON data retrieved from an API. In the fetched JSON data, the title is displayed as title = "F\U00c3\U00b6rdermittel";, which is already UTF-8 encoded by SBJSONParser. Ideally, the string ...

Mongoose Error: Incompatible receiver called Method Uint8Array.length

I am currently working on a small website that incorporates i18n. Initially, I used local json files, but upon transitioning to mongodb, I encountered an unfamiliar error. Any detailed explanation of this issue would be greatly appreciated. The specific e ...

Error: Json conversion to DataModel failed due to parsing issues

I am currently facing an issue while trying to populate a database from a json file. The error I keep encountering is illustrated in the stack trace below. There are two classes involved, namely AppQuestion and IncorrectAnswer, and the data should adhere t ...

A guide to using Selenium WebDriver and C# to interact with checkboxes

My task involves interacting with checkboxes on a webpage, but I'm facing challenges in clicking them. Despite having unique identifiers in the HTML, attempts to click result in an "Element not found" exception. Standard locators have been tested with ...

Manipulating JSON Elements using JavaScript in HTML

My objective is to alternate the visibility between the "prev" and "ext" elements retrieved from the JSON File in the following manner: Here is the link to JS Fiddle The menu bar appears as follows: [ "prev_Person1" "Person1" "ext_Person1" ... "Person2" ...

Tips for verifying the connections between an Angular application and Azure Function (negotiate) when integrating with Azure SignalR Service

I'm working on an angular application that is authenticated with Azure AD, connecting to an Azure Function (negotiate) which then communicates with Azure SignalR service using specific keys. I am looking for guidance on how to authenticate requests ma ...

Sending JSON data from an iOS app to a Flask backend

Within my Flask Python web application, I store certain parameters in SessionStorage to later send back to Flask and save this data as a text file. Interestingly, the process functions perfectly on PCs and Android devices but encounters issues on iOS devi ...