奇怪的结果将字典序列化为JSON

时间:2011-10-21 08:21:34

标签: c# serialization

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

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

1 个答案:

答案 0 :(得分:5)

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