的JavaScriptSerializer:序列清单+字符串转换成JSON [英] JavaScriptSerializer: Serialize a list + a string into JSON
问题描述
我想使用的JavaScriptSerializer发送一个包,包含一个对象列表,以及一个字符串,确定像ChatLogPath JSON数据。至于我可以告诉大家,那类只能序列化一个对象 - 是名单 - 如果我尝试追加多个的它显然只是创建无效的JSON像{...} {...}这将不的工作。
I want to use JavaScriptSerializer to send a package of JSON data that contains both a list of objects as well as a string, identified like ChatLogPath. As far as I can tell, that class can only serialize one object -- being the list -- and if I try to append multiple ones it obviously just creates invalid JSON like {...}{...} which won't work.
有没有办法做到这一点?我疯狂新的C#和ASP.NET MVC所以请原谅我,如果这是一个愚蠢的问题:)
Is there any way to do this? I'm insanely new to C# and ASP.NET MVC so forgive me if this is a dumb question :)
编辑:这里是我的code截至目前
here's my code as of right now.
string chatLogPath = "path_to_a_text_file.txt";
IEnumerable<ChatMessage> q = ...
...
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Serialize(q) + json.Serialize(chatLogPath);
将输出的JSON像这样的阵列{...}其次chatLogPath {...}。换句话说,它不能工作,因为这是无效的JSON
Which will output the array like this in JSON { ... } followed by the chatLogPath { ... }. In other words, it can't work since that's invalid JSON.
推荐答案
要获得与阵列和路径一起单一JSON对象最简单的方法是创建一个类或动态对象,每个作为它的属性/字段。
The easiest way to get a single JSON object with the array and path together is to create a class or dynamic object with each as a property/field of it.
类的例子:
public class ChatInformation {
public IEnumerable<ChatMessage> messages;
public string chatLogPath;
}
...
var output = new ChatInformation {
messages = ...,
chatLogPath = "path_to_a_text_file.txt"
};
return json.Serialize(output);
动态例子(需要.NET 4 +):
Dynamic example (requires .NET 4+):
dynamic output = new ExpandoObject {
messages = ...,
chatLogPath = "path_to_a_text_file.txt"
};
return json.Serialize(output);
匿名类型的例子(如果你不小心有另一个类,也不是你的.NET 4):
Anonymous Type example (if you don't care to have another class, nor are you on .NET 4):
var output = new {
messages = ...,
chatLogPath = "path_to_a_text_file.txt"
};
return json.Serialize(output);
这篇关于的JavaScriptSerializer:序列清单+字符串转换成JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!