0

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

user2765331
  • 155
  • 2
  • 3
  • 10

4 Answers4

0

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?

Community
  • 1
  • 1
ZuoLi
  • 383
  • 2
  • 14
  • i am getting this output in the browser how do i get of the escape characters – user2765331 Nov 06 '14 at 09:00
  • @user2765331, I've updated answer - the problem can be with double json serialization – ZuoLi Nov 06 '14 at 09:15
  • 1
    You have square brackets not because you serialize dictionary but because you serialize list of dictionary. All arrays, list etc are serialized with square brackets. – rraszewski Nov 06 '14 at 09:17
  • i used this too square brackets are removed but i want to get the clean json but the output is like "{\"title\":\"Sathyam\",\"tid\":\"NiZamabad\"}" public class JsonHelper { public static string JsonSerializer(T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, t); string jsonString = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return jsonString; – user2765331 Nov 06 '14 at 09:20
0

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>

rraszewski
  • 1,135
  • 7
  • 21
0

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; }
    }
Ganesh Todkar
  • 507
  • 5
  • 12
0

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)));
Community
  • 1
  • 1
user2765331
  • 155
  • 2
  • 3
  • 10