【问题标题】:How to create JSON string in C#如何在 C# 中创建 JSON 字符串
【发布时间】:2010-11-06 13:37:05
【问题描述】:

我刚刚使用 XmlWriter 创建了一些 XML 以在 HTTP 响应中发回。您将如何创建 JSON 字符串。我假设您只会使用字符串构建器来构建 JSON 字符串,然后它们会将您的响应格式化为 JSON?

【问题讨论】:

    标签: c# asp.net json


    【解决方案1】:

    使用Newtonsoft.Json 会更容易:

    Product product = new Product();
    product.Name = "Apple";
    product.Expiry = new DateTime(2008, 12, 28);
    product.Price = 3.99M;
    product.Sizes = new string[] { "Small", "Medium", "Large" };
    
    string json = JsonConvert.SerializeObject(product);
    

    文档:Serializing and Deserializing JSON

    【讨论】:

    • MS 现在将 NewtonSoft 作为 VS MVC4 项目模板中的标准提供
    • 你也可以在需要的时候序列化匿名对象:string json = JsonConvert.SerializeObject(new { "PropertyA" = obj.PropertyA });.
    • @MattBeckman 我得到“无效的匿名类型成员声明器。匿名类型成员必须使用成员分配、简单名称或成员访问来声明。"PropertyA" 不应该是 PropertyA 吗?
    • 所以我们需要实现一个类和对象,来构造一个简单的json!想象一下嵌套的——不是固定的数组——元素。我不明白为什么空气中有这么多热情!
    • @MattBeckman @Jonah 是 string json = JsonConvert.SerializeObject(new { PropertyA = obj.PropertyA });,PropertyA. 上没有双引号
    【解决方案2】:

    您可以使用JavaScriptSerializer class,检查this 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);
            }
        }
    }
    

    用法:

    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();
    

    【讨论】:

    • 是的,只是想先弄清楚如何形成 JSON 文本。谢谢
    • 如果您不使用 .NET 3.5 怎么办!大**它
    • JavaScriptSerializer 是 ASP.NET Ajax 1.0 的一部分,如果您想从 .NET 2.0 使用它。
    • 您仍然可以使用它。它是 ASP.NET 2.0 AJAX Extensions 1.0 的一部分:asp.net/AJAX/Documentation/Live/mref/…
    • 我们的项目可以在 VS 2008 中打开......所以它在某个时候被转换了。这是否意味着我们现在可以在现有代码库中使用 .NET 3.5?
    【解决方案3】:

    Newtonsoft.Json 和 Newtonsoft.Json.Linq 库的简单使用。

            //Create my object
            var myData = new
            {
                Host = @"sftp.myhost.gr",
                UserName = "my_username",
                Password = "my_password",
                SourceDir = "/export/zip/mypath/",
                FileName = "my_file.zip"
            };
    
            //Tranform it to Json object
            string jsonData = JsonConvert.SerializeObject(myData);
    
            //Print the Json object
            Console.WriteLine(jsonData);
    
            //Parse the json object
            JObject jsonObject = JObject.Parse(jsonData);
    
            //Print the parsed Json object
            Console.WriteLine((string)jsonObject["Host"]);
            Console.WriteLine((string)jsonObject["UserName"]);
            Console.WriteLine((string)jsonObject["Password"]);
            Console.WriteLine((string)jsonObject["SourceDir"]);
            Console.WriteLine((string)jsonObject["FileName"]);
    

    【讨论】:

    • 简单方便。谢谢。
    • 真的在寻找像 PHP 一样简单的东西。谢谢!
    【解决方案4】:

    这个库非常适合来自 C# 的 JSON

    http://james.newtonking.com/pages/json-net.aspx

    【讨论】:

    • 让我问一下,与上面提到的 CMS 的帮助方法相比,使用这个框架有什么好处?
    • 允许您在 json 上获得更精细的粒度,例如您可以指定是否包含空值等
    【解决方案5】:

    此代码 sn-p 使用 .NET 3.5 中 System.Runtime.Serialization.Json 中的 DataContractJsonSerializer。

    public static string ToJson<T>(/* this */ T value, Encoding encoding)
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
    
        using (var stream = new MemoryStream())
        {
            using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding))
            {
                serializer.WriteObject(writer, value);
            }
    
            return encoding.GetString(stream.ToArray());
        }
    }
    

    【讨论】:

    • 所以...取消注释“this”引用以实际让这个 sn-p 工作。如果您以前没有使用过扩展方法,这可能并不明显。
    【解决方案6】:

    您也可以试试我的 ServiceStack JsonSerializer,目前是 fastest .NET JSON serializer。它支持序列化 DataContracts、任何 POCO 类型、接口、包括匿名类型在内的后期绑定对象等。

    基本示例

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

    注意:仅当性能对您不重要时才使用 Microsoft 的 JavaScriptSerializer,因为我不得不将它排除在我的基准测试之外,因为它比其他 JSON 序列化程序慢 40x-100x。

    【讨论】:

    • 我用对象列表尝试了 JsonSerializer.SerializeToString,它只返回了空 json:“[{},{}]”pastebin.com/yEw57L3T 这是我调用 SerializeToString 之前的对象的样子i.imgur.com/dYIE7J1.png不过,这里投票最多的答案有效,返回了我的预期:pastebin.com/aAtB3Gxu
    • 最快的 .NET JSON 序列化程序链接已失效。
    【解决方案7】:

    如果您需要复杂的结果(嵌入式)创建自己的结构:

    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;
            }                
        };
    }
    

    然后你可以通过调用获取JSON字符串

    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);
    

    结果会是这样的:

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

    希望对你有帮助!

    【讨论】:

      【解决方案8】:

      查看 json-net.aspx 项目的 http://www.codeplex.com/json/。为什么要重新发明轮子?

      【讨论】:

      • 取决于,我可能不想仅仅依靠第三方开源插件来创建 JSON。宁愿自己创建字符串/辅助方法。
      【解决方案9】:

      如果您不能或不想使用两个内置 JSON 序列化程序(JavaScriptSerializer 和 DataContractJsonSerializer),您可以尝试使用 JsonExSerializer 库 - 我在许多项目和作品中使用它很好。

      【讨论】:

      • 我已经尝试过 JavaScriptSerializer,但它不适用于 null 对象。
      • @Luke101:到底是怎么回事?我的意思是我每天都在使用它,从来没有遇到过问题,所以我真的很好奇! (没有讽刺意味,我真的很好奇,因为我从来没有遇到过问题)
      【解决方案10】:

      如果您尝试创建 Web 服务以通过 JSON 向网页提供数据,请考虑使用 ASP.NET Ajax 工具包:

      http://www.asp.net/learn/ajax/tutorial-05-cs.aspx

      它会自动将通过 web 服务提供的对象转换为 json,并创建可用于连接它的代理类。

      【讨论】:

      • 这只是对 .ashx 的调用,它会返回一个 JSON 字符串。首先,我只是想弄清楚如何形成字符串..使用 StringBuilder?其次,是的,如何序列化。返回 XML 时,您只需设置响应的内容类型,我认为:context.Response.ContentType = "text/xml"
      【解决方案11】:

      如果您想避免创建类并创建 JSON,请创建动态对象并序列化对象。

                  dynamic data = new ExpandoObject();
                  data.name = "kushal";
                  data.isActive = true;
      
                  // convert to JSON
                  string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
      
      

      像这样读取 JSON 并反序列化:

                  // convert back to Object
                  dynamic output = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
      
                  // read a particular value:
                  output.name.Value
      

      ExpandoObject 来自 System.Dynamic 命名空间。

      【讨论】:

      • 谢谢!这很有帮助。
      【解决方案12】:

      DataContractJSONSerializer 将像 XMLSerializer 一样简单地为您完成所有工作。在网络应用程序中使用它很简单。如果您使用的是 WCF,则可以通过属性指定其用途。 DataContractSerializer 系列也非常快。

      【讨论】:

        【解决方案13】:

        我发现您根本不需要序列化程序。如果您将对象作为列表返回。 让我举个例子。

        在我们的 asmx 中,我们使用传递的变量获取数据

        // return data
        [WebMethod(CacheDuration = 180)]
        public List<latlon> GetData(int id) 
        {
            var data = from p in db.property 
                       where p.id == id 
                       select new latlon
                       {
                           lat = p.lat,
                           lon = p.lon
        
                       };
            return data.ToList();
        }
        
        public class latlon
        {
            public string lat { get; set; }
            public string lon { get; set; }
        }
        

        然后我们使用 jquery 访问服务,传递该变量。

        // get latlon
        function getlatlon(propertyid) {
        var mydata;
        
        $.ajax({
            url: "getData.asmx/GetLatLon",
            type: "POST",
            data: "{'id': '" + propertyid + "'}",
            async: false,
            contentType: "application/json;",
            dataType: "json",
            success: function (data, textStatus, jqXHR) { //
                mydata = data;
            },
            error: function (xmlHttpRequest, textStatus, errorThrown) {
                console.log(xmlHttpRequest.responseText);
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
        return mydata;
        }
        
        // call the function with your data
        latlondata = getlatlon(id);
        

        我们得到了回应。

        {"d":[{"__type":"MapData+latlon","lat":"40.7031420","lon":"-80.6047970}]}
        

        【讨论】:

        • url: "getData.asmx/GetLatLon",因为我希望您的服务器端代码中有 GetLatLon 方法。但是没有。
        【解决方案14】:

        编码用法

        简单对象转 JSON 数组 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);
        

        结果: [[29,"mike"],[5,"dummy"]]

        漂亮的用法

        Pretty print JSON Array PrettyPrintJson() 字符串扩展方法

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

        结果是:

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

        【讨论】:

          【解决方案15】:

          包括:

          使用 System.Text.Json;

          然后像这样序列化你的 object_to_serialize: JsonSerializer.Serialize(object_to_serialize)

          【讨论】:

            猜你喜欢
            • 2013-03-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-01-04
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多