JavaScriptSerializer:将列表+字符串序列化为JSON

con*_*vis 1 c# asp.net-mvc json

我想使用JavaScriptSerializer发送一个JSON数据包,其中包含一个对象列表以及一个标识为ChatLogPath的字符串.据我所知,该类只能序列化一个对象 - 作为列表 - 如果我尝试追加多个对象,它显然只会创建无效的JSON,如{...} {...}工作.

有没有办法做到这一点?我是C#和ASP.NET MVC的新手,所以请原谅我,如果这是一个愚蠢的问题:)

编辑:这是我现在的代码.

    string chatLogPath = "path_to_a_text_file.txt";
    IEnumerable<ChatMessage> q = ...
    ...
    JavaScriptSerializer json = new JavaScriptSerializer();
    return json.Serialize(q) + json.Serialize(chatLogPath);
Run Code Online (Sandbox Code Playgroud)

这将在JSON {...}中输出这样的数组,然后是chatLogPath {...}.换句话说,它无法工作,因为那是无效的JSON.

ven*_*aur 5

将数组和路径放在一起的单个JSON对象的最简单方法是创建一个类或动态对象,每个对象作为它的属性/字段.

类示例:

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);
Run Code Online (Sandbox Code Playgroud)

动态示例(需要.NET 4+):

dynamic output = new ExpandoObject {
  messages = ...,
  chatLogPath = "path_to_a_text_file.txt"
};
return json.Serialize(output);
Run Code Online (Sandbox Code Playgroud)

匿名类型示例(如果您不关心另一个类,也不在.NET 4上):

var output = new {
  messages = ...,
  chatLogPath = "path_to_a_text_file.txt"
};
return json.Serialize(output);
Run Code Online (Sandbox Code Playgroud)