【问题标题】:Strange results serializing a dictionary to JSON将字典序列化为 JSON 的奇怪结果
【发布时间】:2011-10-21 08:21:33
【问题描述】:

我目前正在研究将 WCF 用于 REST 服务。我遇到的一个问题是序列化作为字典的结果。我使用this post 中建议的包装类来序列化由字符串表示的日期(例如“20.10.2011”)和布尔值组成的字典。当我测试结果时,我看到了这个:

{
    "DeparturesResult":
    {
        "_x0032_1.10.2011":true,
        "_x0032_4.10.2011":true,
        "_x0032_6.10.2011":true,
        "_x0032_8.10.2011":true,
        "_x0033_1.10.2011":true
    }
}

..每个键的第一个字符都写成 UTF-8 代码。如果我在字符串前面加上一个字母,我不会遇到这个问题。 (例如 d21.10.2011)

这是我用来序列化字典的代码: 公共类 FlService : IFlService { #region IFlService 成员

    public AjaxDictionary<string, bool> Departures(string from, string to, string portFrom, string portTo)
    {
        var startDate = DateTime.Today; // DateTime.ParseExact(from, "dd.MM.yyyy", null);
        var endDate = DateTime.ParseExact(to, "dd.MM.yyyy", null);
        var client = new Timetables();
        var result = client.GetJourneys(startDate, endDate.AddDays(1), portFrom, portTo);
        var js = result
            .GroupBy(x => x.DepartureTime.CarResToDateTime())
            .Select(x => x.Key)
            .OfType<DateTime>()
            .Select(x => x.Date)
            .Distinct()
            .ToDictionary(x => x.Date.ToString("dd.MM.yyy"), x => true);
        return new AjaxDictionary<string, bool>(js);
    }

    #endregion

    #region Nested type: AjaxDictionary

    [Serializable]
    public class AjaxDictionary<TKey, TValue> : ISerializable
    {
        private readonly Dictionary<TKey, TValue> _dictionary;

        public AjaxDictionary()
        {
            _dictionary = new Dictionary<TKey, TValue>();
        }

        public AjaxDictionary(Dictionary<TKey, TValue> dic)
        {
            _dictionary = dic;
        }

        public AjaxDictionary(SerializationInfo info, StreamingContext context)
        {
            _dictionary = new Dictionary<TKey, TValue>();
        }

        public TValue this[TKey key]
        {
            get { return _dictionary[key]; }
            set { _dictionary[key] = value; }
        }

        #region ISerializable Members

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            foreach (var key in _dictionary.Keys)
                info.AddValue(key is string ? key as string : key.ToString(), _dictionary[key]);
        }

        #endregion

        public void Add(TKey key, TValue value)
        {
            _dictionary.Add(key, value);
        }
    }

    #endregion
}

编辑:为接受的答案添加评论: 这对于 javascript 来说是正确的,但对于 JSON 来说却不是这样。看起来序列化器有点狂热,不仅序列化为 JSON,而且确保 JSON 是 javascript。添加 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON 上的完整 JSON 语法

JSON = null
    or true or false
    or JSONNumber
    or JSONString
    or JSONObject
    or JSONArray

JSONNumber = - PositiveNumber
          or PositiveNumber
PositiveNumber = DecimalNumber
              or DecimalNumber . Digits
              or DecimalNumber . Digits ExponentPart
              or DecimalNumber ExponentPart
DecimalNumber = 0
             or OneToNine Digits
ExponentPart = e Exponent
            or E Exponent
Exponent = Digits
        or + Digits
        or - Digits
Digits = Digit
      or Digits Digit
Digit = 0 through 9
OneToNine = 1 through 9

JSONString = ""
          or " StringCharacters "
StringCharacters = StringCharacter
                or StringCharacters StringCharacter
StringCharacter = any character
                  except " or \ or U+0000 through U+001F
               or EscapeSequence
EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
              or \u HexDigit HexDigit HexDigit HexDigit
HexDigit = 0 through 9
        or A through F
        or a through f

JSONObject = { }
          or { Members }
Members = JSONString : JSON
       or Members , JSONString : JSON

JSONArray = [ ]
         or [ ArrayElements ]
ArrayElements = JSON
             or ArrayElements , JSON

【问题讨论】:

    标签: c# serialization


    【解决方案1】:

    这是因为在 JSON(或 JavaScript)中,键名(或 JavaScript 中的属性)不能以数值开头,因此它会将这些字符放在序列化之后,以确保它们是正确的 JSON 格式

    【讨论】:

    • 您的回答很可能指出了发生这种情况的原因。我用一些背景编辑了这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 2018-09-21
    相关资源
    最近更新 更多