connergdavis
connergdavis

Reputation: 303

JavaScriptSerializer: Serialize a list + a string into 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.

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 :)

Edit: 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);

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.

Upvotes: 1

Views: 10015

Answers (1)

ventaur
ventaur

Reputation: 1851

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.

Class example:

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);

Dynamic example (requires .NET 4+):

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

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);

Upvotes: 5

Related Questions