创建 JSON 对象或字符串..?
我们可以在 C# 中用字符串初始化 JSON 对象吗?
例如: "Person": [{"age":"42","name":"John"}]
as 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);
给出一个字符串: [{},{}]
空数据结构,有什么想法吗?
Can we initialize JSON object with a string in C# ;
like: "Person": [{"age":"42","name":"John"}]
as object JsonData = "Person": [{"age":"42","name":"John"}];
???
So that i can give this JSON object directly to the DatacontractJSONSerializer
And i could get the data out of it.!
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);
}
}
}
So,
string jsonString = ExtensionMethods.JSONHelper.ToJSON(people);
Gives a string of : [{},{}]
Empty data structure, Any idea..?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于扩展方法,您希望将方法修补到要调用该方法的类型上。在这种情况下,
IEnumerable
是添加要在列表上使用的方法的好地方:重要的区别是,您应该针对其定义类型的变量使用扩展方法。您不应该直接引用扩展方法。
With extension methods, you want to patch your method onto the type that you intend to call that method against. In this case,
IEnumerable
is a good place to add methods you want to use on a List:The important distinction is that you should use the extension method against a variable of the type it's defined against. You shouldn't reference the extension method directly.