我有一个如下所示的JSON字符串:
"\"{\\\"MaskedAccountNumber\\\":\\\"4537\\\",\\\"TransactionReferenceNumber\\\":\\\"123\\\"}\""
我想将此JSON转换为NameValueCollection,并且尝试了以下代码。但我收到一个错误 :
string jsonString= "\"{\\\"PersonNumber\\\":\\\"4537\\\",\\\"PersonName\\\":\\\"Jenny\\\"}\""
System.Web.Script.Serialization.JavaScriptSerializer jss1;
NameValueCollection nvc1;
jss1 = new System.Web.Script.Serialization.JavaScriptSerializer();
nvc1 = new NameValueCollection();
try { nvc1 = jss1.Deserialize<NameValueCollection>(jsonString); } catch { }
错误:
无法将类型为“ System.String”的对象转换为类型为“ System.Collections.Specialized.NameValueCollection”
我在哪里弄错了?
答案 0 :(得分:0)
如果您特别需要NameValueCollection
,那么最简单的方法是简单地使用DeserializeObject
,然后将项目添加到NameValueCollection
中,如下所示:
string jsonString= "\"{\\\"PersonNumber\\\":\\\"4537\\\",\\\"PersonName\\\":\\\"Jenny\\\"}\""
System.Web.Script.Serialization.JavaScriptSerializer jss1;
NameValueCollection nvc1;
IDictionary<string, object> dict;
jss1 = new System.Web.Script.Serialization.JavaScriptSerializer();
nvc1 = new NameValueCollection();
dict = jss1.DeserializeObject(jsonString);
foreach (var kvPair in dict)
{
nvc1.Add(kvPair.Key, kvPair.Value);
}
答案 1 :(得分:0)
在Dictionary<string,T>
上给出一个非常简单的扩展方法:
public static class DictionaryExtensions
{
public static NameValueCollection ToNameValueCollection<T>(this IDictionary<string, T> dictionary)
{
var collection = new NameValueCollection();
foreach(var pair in dictionary)
collection.Add(pair.Key, pair.Value?.ToString());
return collection;
}
}
这就像将json反序列化为字典并使用扩展方法一样简单:
var nvc = JsonConvert.DeserializeObject<Dictionary<string,string>>(jsonString)
.ToNameValueCollection();
注意:使用Newtonsoft.Json,但任何反序列化程序都应能够将jsonString
直接反序列化为Dictionary<string,string>
。