可以在c#中使用字符串初始化JSON对象吗?
like: "Person": [{"age":"42","name":"John"}]
作为object JsonData = "Person": [{"age":"42","name":"John"}];
? ?
所以我可以把这个JSON对象直接给DatacontractJSONSerializer
我可以从中得到数据!
List<Person> people = new List<Person>{
new Person{age = 1, name = "Scott"},
new Person{age = 2, name = "Bill"}
};
string jsonString = ExtensionMethods.JSONHelper.ToJSON(people);
}
}
}
namespace ExtensionMethods
{
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
}
string jsonString = ExtensionMethods.JSONHelper.ToJSON(people);
给出一个字符串:[{},{}]
空数据结构,有什么想法吗?
对于扩展方法,您希望将您的方法修补到您打算调用该方法的类型上。在这种情况下,IEnumerable
是添加您想要在List上使用的方法的好地方:
public class Person {
public int age { get; set; }
public string name { get; set; }
}
public static class JSONHelper {
public static string ToJSON(this IEnumerable obj) {
return new JavaScriptSerializer().Serialize(obj);
}
}
void Main() {
List<Person> people = new List<Person> {
new Person() { age = 1, name = "Scott" },
new Person() { age = 2, name = "Bill" }
};
// [{"age":1,"name":"Scott"},{"age":2,"name":"Bill"}]
string json = people.ToJSON();
}
重要的区别在于,您应该针对定义它的类型的变量使用扩展方法。你不应该直接引用扩展方法