how to convert NameValueCollection to JSON string?

后端 未结 4 659
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 10:38

I tried:

  NameValueCollection Data = new NameValueCollection();
  Data.Add(\"foo\",\"baa\");
  string json = new JavaScriptSerializer().Serialize(Data);
         


        
4条回答
  •  囚心锁ツ
    2020-11-28 10:53

    For completeness' sake, and because the question continues to get asked (e.g. here), as long as you are using Json.NET or DataContractJsonSerializer (but not JavaScriptSerializer), you could use the adapter pattern and wrap the NameValueCollection in an IDictionary adapter, and serialize that using any serializer that fully supports serializing arbitrary dictionaries.

    Once such adapter is as follows:

    public class NameValueCollectionDictionaryAdapter : IDictionary
        where TNameValueCollection : NameValueCollection, new()
    {
        readonly TNameValueCollection collection;
    
        public NameValueCollectionDictionaryAdapter() : this(new TNameValueCollection()) { }
    
        public NameValueCollectionDictionaryAdapter(TNameValueCollection collection)
        {
            this.collection = collection;
        }
    
        // Method instead of a property to guarantee that nobody tries to serialize it.
        public TNameValueCollection GetCollection() { return collection; }
    
        #region IDictionary Members
    
        public void Add(string key, string[] value)
        {
            if (collection.GetValues(key) != null)
                throw new ArgumentException("Duplicate key " + key);
            if (value == null)
                collection.Add(key, null);
            else
                foreach (var str in value)
                    collection.Add(key, str);
        }
    
        public bool ContainsKey(string key) { return collection.GetValues(key) != null; }
    
        public ICollection Keys { get { return collection.AllKeys; } }
    
        public bool Remove(string key)
        {
            bool found = ContainsKey(key);
            if (found)
                collection.Remove(key);
            return found;
        }
    
        public bool TryGetValue(string key, out string[] value)
        {
            return (value = collection.GetValues(key)) != null;
        }
    
        public ICollection Values
        {
            get
            {
                return new ReadOnlyCollectionAdapter, string[]>(this, p => p.Value);
            }
        }
    
        public string[] this[string key]
        {
            get
            {
                var value = collection.GetValues(key);
                if (value == null)
                    throw new KeyNotFoundException(key);
                return value;
            }
            set
            {
                Remove(key);
                Add(key, value);
            }
        }
    
        #endregion
    
        #region ICollection> Members
    
        public void Add(KeyValuePair item) { Add(item.Key, item.Value); }
    
        public void Clear() { collection.Clear(); }
    
        public bool Contains(KeyValuePair item)
        {
            string[] value;
            if (!TryGetValue(item.Key, out value))
                return false;
            return EqualityComparer.Default.Equals(item.Value, value); // Consistent with Dictionary
        }
    
        public void CopyTo(KeyValuePair[] array, int arrayIndex)
        {
            foreach (var item in this)
                array[arrayIndex++] = item;
        }
    
        public int Count { get { return collection.Count; } }
    
        public bool IsReadOnly { get { return false; } }
    
        public bool Remove(KeyValuePair item)
        {
            if (Contains(item))
                return Remove(item.Key);
            return false;
        }
    
        #endregion
    
        #region IEnumerable> Members
    
        public IEnumerator> GetEnumerator()
        {
            foreach (string key in collection)
                yield return new KeyValuePair(key, collection.GetValues(key));
        }
    
        #endregion
    
        #region IEnumerable Members
    
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); }
    
        #endregion
    }
    
    public static class NameValueCollectionExtensions
    {
        public static NameValueCollectionDictionaryAdapter ToDictionaryAdapter(this TNameValueCollection collection)
            where TNameValueCollection : NameValueCollection, new()
        {
            if (collection == null)
                throw new ArgumentNullException();
            return new NameValueCollectionDictionaryAdapter(collection);
        }
    }
    
    public class ReadOnlyCollectionAdapter : CollectionAdapterBase>
    {
        public ReadOnlyCollectionAdapter(ICollection collection, Func toOuter)
            : base(() => collection, toOuter)
        {
        }
    
        public override void Add(TOut item) { throw new NotImplementedException(); }
    
        public override void Clear() { throw new NotImplementedException(); }
    
        public override bool IsReadOnly { get { return true; } }
    
        public override bool Remove(TOut item) { throw new NotImplementedException(); }
    }
    
    public abstract class CollectionAdapterBase : ICollection 
        where TCollection : ICollection
    {
        readonly Func getCollection;
        readonly Func toOuter;
    
        public CollectionAdapterBase(Func getCollection, Func toOuter)
        {
            if (getCollection == null || toOuter == null)
                throw new ArgumentNullException();
            this.getCollection = getCollection;
            this.toOuter = toOuter;
        }
    
        protected TCollection Collection { get { return getCollection(); } }
    
        protected TOut ToOuter(TIn inner) { return toOuter(inner); }
    
        #region ICollection Members
    
        public abstract void Add(TOut item);
    
        public abstract void Clear();
    
        public virtual bool Contains(TOut item)
        {
            var comparer = EqualityComparer.Default;
            foreach (var member in Collection)
                if (comparer.Equals(item, ToOuter(member)))
                    return true;
            return false;
        }
    
        public void CopyTo(TOut[] array, int arrayIndex)
        {
            foreach (var item in this)
                array[arrayIndex++] = item;
        }
    
        public int Count { get { return Collection.Count; } }
    
        public abstract bool IsReadOnly { get; }
    
        public abstract bool Remove(TOut item);
    
        #endregion
    
        #region IEnumerable Members
    
        public IEnumerator GetEnumerator()
        {
            foreach (var item in Collection)
                yield return ToOuter(item);
        }
    
        #endregion
    
        #region IEnumerable Members
    
        IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
    
        #endregion
    }
    

    Then an adapted can be constructed for a given NameValueCollection Data simply by doing:

    var adapter = Data.ToDictionaryAdapter();
    

    Notes:

    • Using the adapter may be be more performant than simply creating a copied dictionary, and should work well with any serializer that fully supports dictionary serialization.

      The adapter might also be useful in using a NameValueCollection with any other code that expects an IDictionary of some sort - this is the fundamental advantage of the adapter pattern.

    • That being said, JavaScriptSerializer cannot be used with the adapter because this serializer cannot serialize an arbitrary type implementing IDictionary that does not also inherit from Dictionary. For details see Serializing dictionaries with JavaScriptSerializer.

    • When using DataContractJsonSerializer, a NameValueCollection can be replaced with an adapter in the serialization graph by using the data contract surrogate mechanism.

    • When using Json.NET a NameValueCollection can be replaced with an adapter using a custom JsonConverter such as the following:

      public class NameValueJsonConverter : JsonConverter
          where TNameValueCollection : NameValueCollection, new()
      {
          public override bool CanConvert(Type objectType)
          {
              return typeof(TNameValueCollection).IsAssignableFrom(objectType);
          }
      
          public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
          {
              if (reader.SkipComments().TokenType == JsonToken.Null)
                  return null;
      
              // Reuse the existing NameValueCollection if present
              var collection = (TNameValueCollection)existingValue ?? new TNameValueCollection();
              var dictionaryWrapper = collection.ToDictionaryAdapter();
      
              serializer.Populate(reader, dictionaryWrapper);
      
              return collection;
          }
      
          public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
          {
              var collection = (TNameValueCollection)value;
              var dictionaryWrapper = new NameValueCollectionDictionaryAdapter(collection);
              serializer.Serialize(writer, dictionaryWrapper);
          }
      }
      
      public static partial class JsonExtensions
      {
          public static JsonReader SkipComments(this JsonReader reader)
          {
              while (reader.TokenType == JsonToken.Comment && reader.Read())
                  ;
              return reader;
          }
      }
      

      Which could be used e.g. as follows:

      string json = JsonConvert.SerializeObject(Data, Formatting.Indented, new NameValueJsonConverter());
      
    • NameValueCollection supports all of the following

      • A null value for a given key;
      • Multiple values for a given key (in which case NameValueCollection.Item[String] returns a comma-separated list of values);
      • A single value containing an embedded comma (which cannot be distinguished from the case of multiple values when using NameValueCollection.Item[String]).


      Thus the adapter must implement IDictionary rather than IDictionary and also take care to handle a null value array.

    Sample fiddle (including some basic unit testing) here: https://dotnetfiddle.net/gVPSi7

提交回复
热议问题