簡體   English   中英

將字典序列化為JSON的奇怪結果

[英]Strange results serializing a dictionary to JSON

我目前正在研究將WCF用於REST服務。 我遇到的一個問題是序列化字典的結果。 我以前在建議的包裝類這篇文章連載由字符串表示的日期(如“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

這是因為在JSON(或JavaScript)中,鍵名(或JavaScript中的屬性)不能以數字值開頭,因此它將這些字符序列化后放置以確保它們是正確的JSON格式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM