Creating a JSON array in C#

前端 未结 4 1942
北恋
北恋 2021-01-30 02:04

Ok, so I am trying to send POST commands over an http connection, and using JSON formatting to do so. I am writing the program to do this in C#, and was wondering how I would f

4条回答
  •  一向
    一向 (楼主)
    2021-01-30 03:03

    You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:

    public class Item
    {
        public string name { get; set; }
        public string index { get; set; }
        public string optional { get; set; }
    }
    
    public class RootObject
    {
        public List items { get; set; }
    }
    

    Usage:

    var objectToSerialize = new RootObject();
    objectToSerialize.items = new List 
                              {
                                 new Item { name = "test1", index = "index1" },
                                 new Item { name = "test2", index = "index2" }
                              };
    

    And in the result you won't have to change things several times if you need to change data-structure.

    p.s. Here's very nice tool for complex jsons

提交回复
热议问题