How to create JSON string in C#

后端 未结 14 1004
闹比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

    The DataContractJSONSerializer will do everything for you with the same easy as the XMLSerializer. Its trivial to use this in a web app. If you are using WCF, you can specify its use with an attribute. The DataContractSerializer family is also very fast.

    0 讨论(0)
  • 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"
          ]
       ]
    ]
    
    0 讨论(0)
  • 2020-11-22 13:12

    Include:

    using System.Text.Json;

    Then serialize your object_to_serialize like this: JsonSerializer.Serialize(object_to_serialize)

    0 讨论(0)
  • 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<String> ids = new List<string>() { "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!

    0 讨论(0)
  • 2020-11-22 13:17

    You can also try my ServiceStack JsonSerializer it's the fastest .NET JSON serializer at the moment. It supports serializing DataContracts, any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.

    Basic Example

    var customer = new Customer { Name="Joe Bloggs", Age=31 };
    var json = JsonSerializer.SerializeToString(customer);
    var fromJson = JsonSerializer.DeserializeFromString<Customer>(json); 
    

    Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.

    0 讨论(0)
  • 2020-11-22 13:21

    You could use the JavaScriptSerializer class, check this article to build an useful extension method.

    Code from article:

    namespace ExtensionMethods
    {
        public static class JSONHelper
        {
            public static string ToJSON(this object obj)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                return serializer.Serialize(obj);
            }
    
            public static string ToJSON(this object obj, int recursionDepth)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                serializer.RecursionLimit = recursionDepth;
                return serializer.Serialize(obj);
            }
        }
    }
    

    Usage:

    using ExtensionMethods;
    
    ...
    
    List<Person> people = new List<Person>{
                       new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
                       new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
                       };
    
    
    string jsonString = people.ToJSON();
    
    0 讨论(0)
提交回复
热议问题