Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert long number as string in the serialization

I have a custom made class that use a long as ID. However, when I call my action using ajax, my ID is truncated and it loses the last 2 numbers because javascript loses precision when dealing with large numbers. My solution would be to give a string to my javascript, but the ID have to stay as a long on the server side.

Is there a way to serialize the property as a string? I'm looking for some kind of attribute.

Controller

public class CustomersController : ApiController
{
   public IEnumerable<CustomerEntity> Get()
   {
      yield return new CustomerEntity() { ID = 1306270928525862486, Name = "Test" };
   }
}

Model

public class CustomerEntity
{
   public long ID { get; set; }
   public string Name { get; set; }
}

JSON Result

[{"Name":"Test","ID":1306270928525862400}]
like image 764
Bruno Avatar asked Jun 28 '13 16:06

Bruno


People also ask

What is serialization of string?

String serialization is the process of writing a state of object into a byte stream. In python, the “pickle” library is used for enabling serialization. This module includes a powerful algorithm for serializing and de-serializing a Python object structure.

Can we convert string to long in C#?

long myLong = long. Parse(myString);

What is serialization in C# with example?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.


2 Answers

You could probably create a custom JsonConverter and apply it on your property.

Following is an example (NOTE: I haven't used this api before so it could probably be improved more, but following should give you a rough idea):

public class Person
{
    [JsonConverter(typeof(IdToStringConverter))]
    public long ID { get; set; }

    public string Name { get; set; }
}

public class IdToStringConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken jt = JValue.ReadFrom(reader);

        return jt.Value<long>();
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(System.Int64).Equals(objectType);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value.ToString());
    }
}

Web API Action:

public Person Post([FromBody]Person person)
{
    return person;
}

Request:

POST http://asdfasdf/api/values HTTP/1.1  
Host: servername:9095  
Connection: Keep-Alive  
Content-Type: application/json  
Content-Length: 42  

{"ID":"1306270928525862400","Name":"Mike"}

Response:

HTTP/1.1 200 OK  
Content-Length: 42  
Content-Type: application/json; charset=utf-8  
Server: Microsoft-HTTPAPI/2.0  
Date: Fri, 28 Jun 2013 17:02:18 GMT  

{"ID":"1306270928525862400","Name":"Mike"}

EDIT:
if you do not want to decorate the property with an attribute, you could instead add it to the Converters collection. Example:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IdToStringConverter());
like image 153
Kiran Avatar answered Oct 01 '22 03:10

Kiran


How about a view model that only has string properties, like this:

public class CustomerEntityViewModel
{
    public string ID { get; set; }
    public string Name { get; set; }
}

Now you are only dealing with strings and JSON serialization problems go away.

like image 20
Karl Anderson Avatar answered Oct 01 '22 03:10

Karl Anderson