Ruan Ruan - 2 months ago 9
C# Question

in C# assigning a array name to Json array

I have an Json array that looks like this:

[{"ticketAmount":5,"state":"Active"},{"ticketAmount":6,"state":"Closed"},{"ticketAmount":1,"state":"Resolve"}]


I want it to to get is an array that contains a assigned variable and then the Json, it should look like this(basically giving the array name):

"items":[{"ticketAmount":5,"state":"Active"},{"ticketAmount":6,"state":"Closed"},{"ticketAmount":1,"state":"Resolve"}]


My code:

public class EntityUserClosed
{
public int ticketAmount { get; set; }
public string loggedDate { get; set; }
}

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetUserClosedTickets()
{
var entites = new List<EntityUserClosed>();

using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Select LoggedBy, count(ID) as ticketAmount from Tickets WHERE LoggedDate >=dateadd(day,datediff(day,0,GetDate())- 30,0) AND State = '3' group by LoggedBy"))
{
var ticketAmount = 0;
var loggedBy = string.Empty;

cmd.Connection = con;

con.Open();
var reader = cmd.ExecuteReader();

if (reader.HasRows)
{
while (reader.Read())
{
ticketAmount = (int)reader["ticketAmount"];
//Convert to JSON format
loggedBy = reader["LoggedBy"].ToString();

var entity = new EntityUserClosed
{
ticketAmount = ticketAmount,
loggedDate = loggedBy,
};
entites.Add(entity);
}
}

var json = serializer.Serialize(entites);
this.Context.Response.ContentType = "application/json; charset=utf-8";
var test = json.Replace("\\", "");
this.Context.Response.Write(test);
}
}
}


I have tried a few solutions such as:

var entity = new List<EntityUserClosed>()


but not sure how that would work.

Thanks

L.B L.B
Answer

Simply change your serialization code as follows....

var json = serializer.Serialize(new {items=entites} );

BTW: items:[...] is not a valid json, it should be {items:[...]}