How to return serialized to JSON using C#
Im working with a WCF in which i return JSON. But i get messages looking like
"{\"ids\":[\"id\":1,\"id\":34,\"id\":67,\"id\":100,\"id\":133,\"id\":166,\"id\":199]}"
How do I get rid of the first and last qoutation marks?
EDIT:
public class Ids {
public IdDetails[] ids开发者_高级运维{get;set}
}
public class IdDetails{
public int id {get;set}
}
And here I return JSON
public string GetIds(){
Ids ids = new Ids();
List<IdDetails> idd = new List<IdDetails>();
for(int i=0;i<10; i++){
idd.add(new IdDetails(i+1*33));
}
ids.ids = idd.ToArray();
JavaScriptSerializer jSerialize = new JavaScriptSerializer();
string json = jSerialize.Serialize(ids);
return ids;
}
*EDIT 2: SOLVED *
The method shouldn't return a string. It should return a Ids-object. No need to serialize. Set the ResponseFormat = WebMassageFormat.Json and it will work.
Thanks anyways!
Are you looking with the Visual Studio Debugger at the string?
The debugger shows strings as C# string literal. The string itself doesn't actually contain the leading and trailing "
characters and the \
characters.
Console.WriteLine(s);
Output:
{"ids":["id":1,"id":34,"id":67,"id":100,"id":133,"id":166,"id":199]}
JavaScriptSerializer Class
The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize the data that is passed between the browser and the Web server. You cannot access that instance of the serializer. However, this class exposes a public API. Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.
To serialize an object, use the Serialize method. To deserialize a JSON string, use the Deserialize or DeserializeObject methods. To serialize and deserialize types that are not natively supported by JavaScriptSerializer, implement custom converters by using the JavaScriptConverter class. Then register the converters by using the RegisterConverters method.
I've used it in non-web applications.
精彩评论