Question

I am new to WCF. I created one WCF service and returned the data as JSON data. I assigned the return data to GridView, it shows the data perfectly.

[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate="employee/{search}")] 
List<Employee> Listing(string search);

Now, I want to display the JSON string in <div> element (to verify the data). I tried to show the return data,

dvJson.InnerHtml = esc.Listing("s");

it shows like this

Employee[]

How to display JSON string in div element using C#?

Thanks in advance.

Was it helpful?

Solution

I found the solution...

  JavaScriptSerializer serializer = new JavaScriptSerializer();
  StringBuilder sb = new StringBuilder();
  serializer.Serialize(esc.Listing("s"), sb);
  dvJson.InnerHtml = sb.ToString();

Output:

  [{"ID":1,"Name":"Raja"},{"ID":2,"Name":"Manisha"},{"ID":4,"Name":"Sam"},{"ID":7,"Name":"Suresh"}]

Using DataContractJsonSerializer (Pranav Singh code updated [2-4 lines])

To avoid Type information, set JSON Serializer setting EmitTypeInformation to "Never", from JSON data.

  MemoryStream stream1 = new MemoryStream();
  DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
  settings.EmitTypeInformation = System.Runtime.Serialization.EmitTypeInformation.Never;
  DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Employee>), settings);
  ser.WriteObject(stream1, esc.Listing("s"));
  stream1.Position = 0;
  StreamReader sr = new StreamReader(stream1);
  dvJson.InnerHtml = sr.ReadToEnd();

Thanks

OTHER TIPS

Use the DataContractJsonSerializer class, refer DataContractJsonSerializer Class

It's better than JavaScriptSerializer because it can also safely deserialize objects from a JSON string and it part of WCF.

Usage :

    MemoryStream stream1 = new MemoryStream();
    DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (List<Employee>));
    ser.WriteObject(stream1, esc.Listing("s"));
    stream1.Position = 0;
    StreamReader sr = new StreamReader(stream1);
    dvJson.InnerHtml = sr.ReadToEnd();

To avoid Type information (replace the 2nd line with following code)

JSON Serializer setting: Set EmitTypeInformation to "Never" to avoid "__Type" information from the JSON data.

    DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
    settings.EmitTypeInformation = System.Runtime.Serialization.EmitTypeInformation.Never;
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Employee>), settings);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top