Click here to Skip to main content
15,921,169 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am working with wcf webservice with json format string. my code is

[ServiceContract(Name = "StudentInformation")]
public interface IService1
{

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
UriTemplate = "GetStudentDetails/{Userid}/{Password}/{EntityId}/{RequestAction}/{RequestFilter}")]

string GetStudentDetails(string Userid, string Password, string EntityId, string RequestAction, string RequestFilter);
}


// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract(Name = "StudentInfo")]
public class StudentList
{

[DataMember(Order = 1, Name = "StudentId")]
private string idStudent;
public string P_idstudent
{
get
{
return idStudent;
}
set
{
idStudent = value;
}
}

[DataMember(Order = 2, Name = "Student Type")]
private string StudentType;
public string P_Studenttype
{
get
{
return StudentType;
}
set
{
StudentType = value;
}
}

}


public class Service1 : IService1
{
public string GetStudentDetails(string Userid, string Password, string EntityId, string RequestAction, string RequestFilter)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ToString());

List<studentlist> lStudentList = new List<studentlist>();
string sql = "select * from student";
SqlCommand command = new SqlCommand(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
StudentList SList = new StudentList();
for (int i = 0; i < dt.Rows.Count; i++)
{

SList.P_idstudent = dt.Rows[i]["idstudent"].ToString();
SList.P_Studenttype = dt.Rows[i]["type"].ToString();
lStudentList.Add(SList);

}
DataContractJsonSerializer serializer = new DataContractJsonSerializer(lStudentList.GetType());
MemoryStream memoryStream = new MemoryStream();
serializer.WriteObject(memoryStream, lStudentList);

string json = Encoding.Default.GetString(memoryStream.ToArray());
return json;

}
}


I am getting the json formatted result.

[{"StudentId":"2","Student Type":"1"},{"StudentId":"2","Student Type":"1"}]



but I need the results like

{“studentInfo” : [{"StudentId":"2","Student Type":"1"},{"StudentId":"2","Student Type":"1"}]}

what can i do to get the output concated “studentInfo” :
Posted

1 solution

DataContractJsonSerializer has some bugs. Try other JSON serializers, like FastJSON[^] or Json.NET[^].
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900