Reputation: 2144
I have the following code in .NET
public JsonResult<string> Get()
{
Message message1 = new Message("lala1");
Message message2 = new Message("lala2");
List<Message> listOfMessages = new List<Message>();
listOfMessages.Add(message1);
listOfMessages.Add(message2);
var json = new JavaScriptSerializer().Serialize(listOfMessages);
return Json(json);
}
What I get as a result is:
"[{\"message\":\"lala1\"},{\"message\":\"lala2\"}]"
I do not want the double quotes (""
) in the start and in the end. Why does it add them ?
Upvotes: 0
Views: 717
Reputation: 2144
Solved it by using and returning a List Of JObjects.
Upvotes: 0
Reputation: 2487
MSDN documentation for JavaScriptSerializer
class actually recommends the following:
Json.NET should be used [for] serialization and deserialization.
JSON.NET library became de-facto standard for working with JSON in .NET, for example, it is a default serializer that is used with ASP.NET Web API (link).
Here is how you can re-write your code to use JSON.NET (be sure to add Newtonsoft.Json nuget package to your solution):
public static void Main()
{
var result = SerializeMessages();
Console.WriteLine(result);
}
public static string SerializeMessages()
{
var listOfMessages = new List<Message>
{
new Message("lala1"),
new Message("lala2")
};
return JsonConvert.SerializeObject(listOfMessages);
}
Upvotes: 1
Reputation: 1549
You are trying to serialize JSON in JSON. Change :
var json = new JavaScriptSerializer().Serialize(listOfMessages);
return Json(json);
to :
return Json(listOfMessages);
Upvotes: 2