如何将NameValueCollection转换为JSON字符串?

49

我尝试了:

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

它返回:["foo"] 我期望得到的是 {"foo" : "baa"},我该怎么做?

4个回答

61

将NameValueCollection序列化的一种方法是先将其转换为Dictionary,然后再对Dictionary进行序列化。要转换为Dictionary:

thenvc.AllKeys.ToDictionary(k => k, k => thenvc[k]);
如果您需要经常进行转换,您也可以创建一个扩展方法来处理NameValueCollection:
public static class NVCExtender
{
    public static IDictionary<string, string> ToDictionary(
                                        this NameValueCollection source)
    {
        return source.AllKeys.ToDictionary(k => k, k => source[k]);
    }
}

那么你可以像这样在一行中完成转换:

NameValueCollection Data = new NameValueCollection();
Data.Add("Foo", "baa");

var dict = Data.ToDictionary();

然后您可以将字典序列化:

var json = new JavaScriptSerializer().Serialize(dict);
// you get {"Foo":"baa"}

但是 NameValueCollection 可以针对一个键包含多个值,例如:

NameValueCollection Data = new NameValueCollection();
Data.Add("Foo", "baa");
Data.Add("Foo", "again?");

如果您序列化这个对象,你将得到{"Foo":"baa,again?"}

你可以修改转换器以生成IDictionary<string, string[]>

public static IDictionary<string, string[]> ToDictionary(
                                    this NameValueCollection source)
{
    return source.AllKeys.ToDictionary(k => k, k => source.GetValues(k));
}

你可以这样获取序列化的值:{"Foo":["baa","again?"]}


41

NameValueCollection不是一个IDictionary,所以JavaScriptSerializer无法直接按照您期望的方式对其进行序列化。您需要先将其转换为字典,然后再进行序列化。

更新:由于涉及到一个键有多个值的问题,调用nvc[key]将简单地返回它们由逗号分隔的内容,这可能会满足需求。如果不行,可以始终调用GetValues并根据需要处理这些值。下面的代码已进行了更新,展示了一种可能的方法。

public class StackOverflow_7003740
{
    static Dictionary<string, object> NvcToDictionary(NameValueCollection nvc, bool handleMultipleValuesPerKey)
    {
        var result = new Dictionary<string, object>();
        foreach (string key in nvc.Keys)
        {
            if (handleMultipleValuesPerKey)
            {
                string[] values = nvc.GetValues(key);
                if (values.Length == 1)
                {
                    result.Add(key, values[0]);
                }
                else
                {
                    result.Add(key, values);
                }
            }
            else
            {
                result.Add(key, nvc[key]);
            }
        }

        return result;
    }

    public static void Test()
    {
        NameValueCollection nvc = new NameValueCollection();
        nvc.Add("foo", "bar");
        nvc.Add("multiple", "first");
        nvc.Add("multiple", "second");

        foreach (var handleMultipleValuesPerKey in new bool[] { false, true })
        {
            if (handleMultipleValuesPerKey)
            {
                Console.WriteLine("Using special handling for multiple values per key");
            }
            var dict = NvcToDictionary(nvc, handleMultipleValuesPerKey);
            string json = new JavaScriptSerializer().Serialize(dict);
            Console.WriteLine(json);
            Console.WriteLine();
        }
    }
}

3
NameValueCollection 可以拥有一个键对应多个值,但它并不能解决这个问题。 - zzzzBov
这个方法很可能会引发异常!NameValueCollection 存在的原因(以及 .NET 有时不使用字典的原因)是为了允许每个键有多个值。字典要求每个值只有一个键。 - John Culviner
1
该方法不会抛出异常。如果有多个键,则 nvc[key] 只会返回它们由逗号 , 连接的字符串。但为了完整起见,我更新了答案以更明确地说明这一点。 - carlosfigueira
如果查询字符串还没有转换为NameValueCollection,则可以使用以下方法:https://dev59.com/M2cs5IYBdhLWcg3w-Yz4 - sobelito
1
DotNetFiddle:NameValueCollection 上的多个键 https://dotnetfiddle.net/hnYwGn - Rodrigo Groener

3
为了完整起见,并且因为这个问题仍然被问到(例如这里),只要您使用Json.NET或(但不是),您可以使用适配器模式并将包装在IDictionary<string,string[]>适配器中,并使用任何完全支持序列化任意字典的序列化器对其进行序列化。
其中一个这样的适配器如下:
public class NameValueCollectionDictionaryAdapter<TNameValueCollection> : IDictionary<string, string[]>
    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<string,string[]> 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<string> 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<string[]> Values
    {
        get
        {
            return new ReadOnlyCollectionAdapter<KeyValuePair<string, string[]>, 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<KeyValuePair<string,string[]>> Members

    public void Add(KeyValuePair<string, string[]> item) { Add(item.Key, item.Value); }

    public void Clear() { collection.Clear(); }

    public bool Contains(KeyValuePair<string, string[]> item)
    {
        string[] value;
        if (!TryGetValue(item.Key, out value))
            return false;
        return EqualityComparer<string[]>.Default.Equals(item.Value, value); // Consistent with Dictionary<TKey, TValue>
    }

    public void CopyTo(KeyValuePair<string, string[]>[] 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<string, string[]> item)
    {
        if (Contains(item))
            return Remove(item.Key);
        return false;
    }

    #endregion

    #region IEnumerable<KeyValuePair<string,string[]>> Members

    public IEnumerator<KeyValuePair<string, string[]>> GetEnumerator()
    {
        foreach (string key in collection)
            yield return new KeyValuePair<string, string[]>(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<TNameValueCollection> ToDictionaryAdapter<TNameValueCollection>(this TNameValueCollection collection)
        where TNameValueCollection : NameValueCollection, new()
    {
        if (collection == null)
            throw new ArgumentNullException();
        return new NameValueCollectionDictionaryAdapter<TNameValueCollection>(collection);
    }
}

public class ReadOnlyCollectionAdapter<TIn, TOut> : CollectionAdapterBase<TIn, TOut, ICollection<TIn>>
{
    public ReadOnlyCollectionAdapter(ICollection<TIn> collection, Func<TIn, TOut> 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<TIn, TOut, TCollection> : ICollection<TOut> 
    where TCollection : ICollection<TIn>
{
    readonly Func<TCollection> getCollection;
    readonly Func<TIn, TOut> toOuter;

    public CollectionAdapterBase(Func<TCollection> getCollection, Func<TIn, TOut> 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<TOut> Members

    public abstract void Add(TOut item);

    public abstract void Clear();

    public virtual bool Contains(TOut item)
    {
        var comparer = EqualityComparer<TOut>.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<TOut> Members

    public IEnumerator<TOut> GetEnumerator()
    {
        foreach (var item in Collection)
            yield return ToOuter(item);
    }

    #endregion

    #region IEnumerable Members

    IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }

    #endregion
}

然后,可以通过以下方式为给定的NameValueCollection Data构建一个适配器:
var adapter = Data.ToDictionaryAdapter();

翻译:注释:
  • 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<TKey, TValue> that does not also inherit from Dictionary<TKey, TValue>. 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<TNameValueCollection> : 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<TNameValueCollection>(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>());
    
  • 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<string, string[]> rather than IDictionary<string, string> and also take care to handle a null value array.

这里有一个示例fiddle(包括一些基本的单元测试):https://dotnetfiddle.net/gVPSi7

3
如果您的字典不打算包含太多条目,您可以使用类:System.Collections.Specialized.ListDictionary

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接