[英]How can I convert json string (complex object) to NameValueCollection?
I want to convert a json string to NameValueCollection. 我想将json字符串转换为NameValueCollection。 I came up with the code below.
我想出了下面的代码。
public static NameValueCollection ConvertFromJson(string json)
{
var anonymous = JContainer.Parse(json);
var nvc = new NameValueCollection();
var dict = new RouteValueDictionary(anonymous);
foreach (var kvp in dict)
{
if (kvp.Value == null)
{
// I am OK if a property is null. Just skip it.
continue;
}
if (kvp.Value.GetType().Name.Contains("Anonymous"))
{
var prefix = kvp.Key + ".";
foreach (var innerkvp in new RouteValueDictionary(kvp.Value))
{
nvc.Add(prefix + innerkvp.Key, innerkvp.Value.ToString());
}
}
else
{
nvc.Add(kvp.Key, kvp.Value.ToString());
}
}
return nvc;
}
It works well with normal classes but not nested classes. 它适用于普通类,但不适用于嵌套类。 For example, it works with
class A
but not class B
. 例如,它适用于
class A
但不适用于class B
。
class A
{
public string AAA { get; set; }
public int BBB { get; set; }
}
class B
{
public string AAA { get; set; }
public MyOtherClass BBB { get; set; }
}
How can I convert nested objects to NameValueCollection? 如何将嵌套对象转换为NameValueCollection?
Explain 说明
This question is absolutely not duplicate with How to convert json to NameValueCollection . 这个问题与如何将json转换为NameValueCollection绝对不重复。 The answer in that question only works with
class A
but it does not work with class B
. 该问题的答案仅适用于
class A
但不适用于class B
。
If you only whant to serialise/deserialise a nested object like you shared on the question you could use a work around like this: 如果您只想序列化/反序列化嵌套对象(如您在问题上共享的那样),则可以使用以下解决方法:
Dictionary <string, object> deserializedresult = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
The only problem with it that you need to serialise and desrialise again the nested objects or use reflection to reach the contained elements of the nested objects. 唯一的问题是,您需要再次对嵌套对象进行序列化和反序列化,或者使用反射来到达嵌套对象中包含的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.