简体   繁体   中英

how to Return json format in wcf

iam new to the wcf. iam developing wcf restful

iam returning string by serializing into json format by using the below code

public string ConvertDataTabletoString()
    {
        DataTable dt = new DataTable();
        using (SqlConnection con = new SqlConnection("Data Source=mar-pc;database=user;User    ID=sa;Password=123123;"))
        {
            using (SqlCommand cmd = new SqlCommand("select title=tname,tid=taddress from userdetails where userid='1'", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                Dictionary<string, object> row;
                foreach (DataRow dr in dt.Rows)
                {
                    row = new Dictionary<string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        row.Add(col.ColumnName, dr[col]);
                    }
                    rows.Add(row);
                }
                return serializer.Serialize(rows);
            }
        }
    }

where iam getting the result as

"[{\\"title\\":\\"Sathyam\\",\\"tid\\":\\"NiZamabad\\"}]"

i want to get the result as

{"title":"Sathyam","tid":"Nizamabad"}

iam the operation contract and

 [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "MyGetData/{value}/{password}")]

Help me i tried bodystyle as wrapped also no

You have square brakets besause you serialize a list of dictionaries, not a single object.

Maybe the problem with escape characters is with double-serialization: you already use ResponseFormat = WebMessageFormat.Json and serialize dictionary inside the convertion method. Have a look on this question: How do I return clean JSON from a WCF Service?

Is ConvertDataTabletoString() method called from WCF service method? If yes then you don't have to serialize List<Directory> manually, because it is WCF framework job.

In my opinion your code should be:

public List<Dictionary<string, object>> ConvertDataTabletoString()
{
   // your prev code ...
   return rows;               
}

And in WCF service method you should just return List<Dictionary<string, object>

You can use the following way to solve ur issue :

  [ServiceContract]
    public interface IService
    {

 [WebGet(UriTemplate = "GetStates", ResponseFormat = WebMessageFormat.Json)]
        [OperationContract]
        List<ServiceData> GetStates();
  }

And in Service.cs

        public List<ServiceData> GetStates()
        {
            using (var db = new local_Entities())
            {

                var statesList = db.States.ToList();

                return statesList.Select(state => new ServiceData
                {
                    Id = state.StateId, Value = state.StateName
                }).OrderBy(s => s.Value).ToList();

            }
        }

Note you have to just return the return type collection, at my end I have a List of ServiceData 
  public class ServiceData
    {
        public int Id { get; set; }
        public string Value { get; set; }
    }

i got the answer here Returning raw json (string) in wcf

changed the return type from string to stream and added this part at the end

   WebOperationContext.Current.OutgoingResponse.ContentType ="application/json; charset=utf-8";
   return new MemoryStream(Encoding.UTF8.GetBytes(serializer.Serialize(rows)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM