在序列化中将长数字转换为字符串

在序列化中将长数字转换为字符串

本文介绍了在序列化中将长数字转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的类,它使用一个长 ID.但是,当我使用 ajax 调用我的操作时,我的 ID 被截断并丢失了最后 2 个数字,因为 javascript 在处理大数字时会失去精度.我的解决方案是为我的 javascript 提供一个字符串,但 ID 必须在服务器端保持很长时间.

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.

控制器

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

型号

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

JSON 结果

[{"Name":"Test","ID":1306270928525862400}]

推荐答案

您或许可以创建一个自定义的 JsonConverter 并将其应用于您的财产.

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

以下是一个例子(注意:我以前没有使用过这个api,所以它可能会得到更多的改进,但下面应该给你一个粗略的想法):

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 操作:

Web API Action:

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

请求:

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"}

回复:

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"}

编辑:
如果您不想使用属性装饰该属性,则可以将其添加到 Converters 集合中.示例:

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());

这篇关于在序列化中将长数字转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 13:12