How to create JSON string in C#

后端 未结 14 1159
闹比i
闹比i 2020-11-22 12:39

I just used the XmlWriter to create some XML to send back in an HTTP response. How would you create a JSON string. I assume you would just use a stringbuilder to build the

14条回答
  •  一个人的身影
    2020-11-22 13:13

    If you need complex result (embedded) create your own structure:

    class templateRequest
    {
        public String[] registration_ids;
        public Data data;
        public class Data
        {
            public String message;
            public String tickerText;
            public String contentTitle;
            public Data(String message, String tickerText, string contentTitle)
            {
                this.message = message;
                this.tickerText = tickerText;
                this.contentTitle = contentTitle;
            }                
        };
    }
    

    and then you can obtain JSON string with calling

    List ids = new List() { "id1", "id2" };
    templateRequest request = new templeteRequest();
    request.registration_ids = ids.ToArray();
    request.data = new templateRequest.Data("Your message", "Your ticker", "Your content");
    
    string json = new JavaScriptSerializer().Serialize(request);
    

    The result will be like this:

    json = "{\"registration_ids\":[\"id1\",\"id2\"],\"data\":{\"message\":\"Your message\",\"tickerText\":\"Your ticket\",\"contentTitle\":\"Your content\"}}"
    

    Hope it helps!

提交回复
热议问题