开发者

Formatting the Json serializarion in a .NET Web Service

I have the following .NET web service with the following signature (IServices.cs):

 [OperationContract]
        [WebInvoke(Method = "GET",
             BodyStyle = WebMessageBodyStyle.Bare,
             ResponseFormat = WebMessageFormat.Json)]
        string ReturnListOfPersons();

The implementation is (in the Services.svc.cs):

public string ReturnListOfPersons(){
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Person> listPersons= myModel.ReturnPersons();
var myList = from a in listPersons 
             select new { FirtName = a.FirstName; LastName = a.LastName};                    
string strJSon = oSerializer.Serialize(myList.Distinct());
StringBuilder sbJSon = new StringBuilder();
sbJSon.AppendFormat("{0}", strJSon);
return sbJSon.ToString();
}

The code above is simplified because I have some joins and "try catches".

Anyway, the problem is that the returned json string is :

"[{\"FirstName\":\"Foo\",\"LastName\":\"Bar\"},{\"Hello\":\"Foo\",\"LastName\":\"World\"}]"

W开发者_Python百科ell, it's normal because of the "toString" method. But, I'm trying to get the exact Json format: without the double quotes in the beginning and of course, without the backslashes with the ability to escape the special chars. So, I would get:

[{"FirstName":"Foo","LastName":"Bar"},{"Hello":"Foo","LastName":"World"}]

Is it possible?

Thank you,

Regards


Your first example is not valid JSON. This is what you see in Visual Studio debugger which escapes the strings. What is actually sent is the second.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜