How to create JSON string in C#

后端 未结 14 1194
闹比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:12

    Encode Usage

    Simple object to JSON Array EncodeJsObjectArray()

    public class dummyObject
    {
        public string fake { get; set; }
        public int id { get; set; }
    
        public dummyObject()
        {
            fake = "dummy";
            id = 5;
        }
    
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append('[');
            sb.Append(id);
            sb.Append(',');
            sb.Append(JSONEncoders.EncodeJsString(fake));
            sb.Append(']');
    
            return sb.ToString();
        }
    }
    
    dummyObject[] dummys = new dummyObject[2];
    dummys[0] = new dummyObject();
    dummys[1] = new dummyObject();
    
    dummys[0].fake = "mike";
    dummys[0].id = 29;
    
    string result = JSONEncoders.EncodeJsObjectArray(dummys);
    

    Result: [[29,"mike"],[5,"dummy"]]

    Pretty Usage

    Pretty print JSON Array PrettyPrintJson() string extension method

    string input = "[14,4,[14,\"data\"],[[5,\"10.186.122.15\"],[6,\"10.186.122.16\"]]]";
    string result = input.PrettyPrintJson();
    

    Results is:

    [
       14,
       4,
       [
          14,
          "data"
       ],
       [
          [
             5,
             "10.186.122.15"
          ],
          [
             6,
             "10.186.122.16"
          ]
       ]
    ]
    

提交回复
热议问题