If you want to return complex types in WCF and have them be serialized correctly to JSON, you need to create a data contract. A data contract is simply a class to contain the data to be serialized, where the class is marked with a [DataContract]
attribute and each member of that class you want to be serialized is marked with a [DataMember]
attribute. For example:
[DataContract]
public class Person
{
[DataMember(Name="firstname")]
public string FirstName { get; set; }
[DataMember(Name="lastname")]
public string LastName { get; set; }
}
With the data contract in place, change your service method to build and return an instance of that class instead of a string. For example:
Person SampleJSON(string name)
{
Person p = new Person
{
FirstName = "samplefirstname",
LastName = "samplelastname"
}
return p;
}
WCF will handle the serialization of the data to JSON automatically. If you try to serialize it manually first, then you will get double-serialized string which contains backslashes, as you have seen.
If you have some reason that you need to handle the serialization manually, then you will either have to replace or work around WCF's serializer. See this answer for a starting point.