0

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

1 Answer 1

1

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:[...]}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.