Customize the serialization of a single object in Newtonsoft.Json

When comparing hashes of serialized objects on the server and client, it is important for the JSON rendering to be identical on both sides. Currently, there is an issue with a number field being serialized differently in JavaScript and .NET - causing the hashes to not match.

In JavaScript, the number field serializes as "duration": 1, while in .NET it serializes as "duration": 1.0. This discrepancy is leading to mismatched hashes.

How can I get .NET to serialize without adding the trailing zero?

Answer №1

If you want to customize the format of a float, you can create a custom JsonConverter. It's important to test it with your expected range of values to ensure the formatting is correct.

class CustomFloatConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(float));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteRawValue(((float)value).ToString("0.########"));
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Using JsonConvert.SerializeObject with your custom converter is simple:

string json = JsonConvert.SerializeObject(yourObject, new CustomFloatConverter());

Try it out on this Fiddle: https://dotnetfiddle.net/3t6RiR

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

Looking through a Json file and retrieving data with the help of Javascript

I am currently working on developing a dictionary application for FirefoxOS using JavaScript. The structure of my JSON file is as follows: [ {"id":"3784","word":"Ajar","type":"adv.","descr":" Slightly turned or opened; as, the door was standing ajar.","tr ...

How can I retrieve all links using XPath in Puppeteer when there are issues with pausing or functionality?

I am having issues with using XPaths to select all links on a page in my Puppeteer app. Sometimes the method I am using gets stuck and causes my crawler to pause. I'm wondering if there is a better way to retrieve all links from an XPath or if there m ...

What is the best way to iterate through all values in a LinkedTreeMap with the keys as Strings and the values as

I am facing an issue where I have a JSON file and all the data is stored in a LinkedTreeMap<String, Object>. The problem arises when one of the JSON fields becomes complex: { "val1": "1", "val2": "2", "val3": { "embVal1": "emb1", ...

Various conditional statements based on the dropdown menu choice

I currently have a basic dropdown menu on my webpage that enables users to switch between viewing Actual or Planned dates/times in a table (I am utilizing the controller as syntax): <select ng-model="trip.viewType"> <option value="actual"> ...

Can the ASP.Net website be pre-compiled on an inactive IIS 6 site?

Managing 2 sites on IIS can be a bit tricky. One is the live site, while the other is meant to be accessed only during maintenance periods. During deployment, I typically stop the live site and start up the maintenance site to inform users about the ongoi ...

What is the best way to obtain an array of JSON objects using PHP?

I've been working on code to retrieve data in JSON format, but it's not exactly in the format I need. Can someone assist me in resolving this issue? while ($row = $get_postid->fetch_array()) { $comment_id[]=$row[& ...

React file viewer failing to display content via Firebase storage URLs

This code snippet is designed to display PDF files uploaded to Firebase storage using React. Here is a sample of the code: import ReactDOM from "react-dom"; import FileViewer from "react-file-viewer"; import "./styles.css"; ...

All-in-One MVC Site

I came across a fascinating .net framework that enabled an exe to contain a complete website and server, making deployment as simple as stopping the exe and starting the new one. I am searching for this framework or any similar ones for the .net runtime. ...

Developing a dynamic modal using Angular and embedding Google Maps within an iframe

I'm currently working on implementing a modal in my Angular application that, when opened, displays Google Maps within an iframe. The problem I'm facing is that the iframe isn't loading and I'm receiving this error in the browser conso ...

How to generate a JSON array in bash using jq

I am currently in the process of retrieving information from my various file hosting accounts where I store a lot of backup media. Using megatools, I fetch account details which are then organized into an array and flattened using \n for raw input. A ...

Insert, delete, and modify rows within the table

I'm struggling with a JavaScript issue and could use some help. How can I add a new row for all columns with the same properties as the old rows, including a "remove" button for the new row? Is there a way to prevent editing cells that contain b ...

Utilize the useRef hook in React to enable copying text to the clipboard

Looking to implement a copy to clipboard functionality in React using the useRef hook? Want to accomplish this without relying on any additional libraries? Take a look at my code snippet below. Currently, I'm encountering an error stating myRef.curren ...

Tips for incorporating "are you sure you want to delete" into Reactjs

I am currently working with Reactjs and Nextjs. I have a list of blogs and the functionality to delete any blog. However, I would like to display a confirmation message before deleting each item that says "Are you sure you want to delete this item?" How ...

Conceal a card once verified within a bootstrap modal upon successful AJAX completion

On my delete page, there are multiple posts with a delete button. When the delete button is clicked, a Bootstrap modal opens asking for confirmation "Are you sure you want to delete this post? YES : NO" If the YES button is clicked, the .click(function(e) ...

Tips for narrowing down table searches to only rows containing certain text within a column

Currently, I have a function that allows me to search through my table: //search field for table $("#search_field").keyup(function() { var value = this.value; $("#menu_table").find("tr").each(function(index) { if (index === 0) return; var id = $( ...

Utilizing Timer Control in C# to showcase call duration in the format of hours, minutes, and seconds (HH:

One of the programs I've been working on displays call durations in the format HH:MM:SS. Users have the ability to put a call on hold and take another one. Do I need to trigger a new timer to start from the beginning in this scenario? I'm conside ...

In search of a new object value to update

Looking to update the value of a specific object key in an array? Here is the code snippet where I want to make this change. I only want to replace the value under Mon, not the entire array length. The key weekday will be provided dynamically. array = [ ...

Implementing translation text into a PHP database

<!doctype html> <html> <head> <meta charset="utf-8"> <title>Translate and Save Text</title> </head> <body> <form action="" method="post" name="theform"> <table width="693" border="1" style="table-l ...

Tips for transferring information between two distinct pages utilizing the jQuery POST technique

I'm dealing with two PHP files called card_process.php and payment.php. My goal is to transfer data from the cart_process page to the payment page. Here's a snippet of the code: In cart_process.php: $paynow = "<button type='submit' ...

Discover the magic of retrieving element background images on click using jQuery

I am attempting to extract the value for style, as well as the values inside this tag for background-image. Here is the script I have tried: function getImageUrl(id){ var imageUrl = jQuery("."+id+". cycle-slide").attr("src"); alert('' + ima ...