简体   繁体   English

如何将 C# object 变成 Z303CB0EF9EDB9082D61BBBE5825D972 中的 JSON 字符串?

[英]How do I turn a C# object into a JSON string in .NET?

I have classes like these:我有这样的课程:

class MyDate
{
    int year, month, day;
}

class Lad
{
    string firstName;
    string lastName;
    MyDate dateOfBirth;
}

And I would like to turn a Lad object into a JSON string like this:我想将Lad object 变成JSON字符串,如下所示:

{
    "firstName":"Markoff",
    "lastName":"Chaney",
    "dateOfBirth":
    {
        "year":"1901",
        "month":"4",
        "day":"30"
    }
}

(Without the formatting). (没有格式化)。 I found this link , but it uses a namespace that's not in .NET 4 .我找到了这个链接,但它使用的命名空间不在.NET 4中。 I also heard about JSON.NET , but their site seems to be down at the moment, and I'm not keen on using external DLL files.我也听说过JSON.NET ,但他们的网站目前似乎已关闭,而且我不热衷于使用外部 DLL 文件。

Are there other options besides manually creating a JSON string writer?除了手动创建JSON字符串编写器之外,还有其他选项吗?

Since we all love one-liners既然我们都喜欢单线

... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer. ... 这个依赖于 Newtonsoft NuGet package,它比默认的序列化程序更受欢迎并且更好。

Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})

Documentation: Serializing and Deserializing JSON文档: 序列化和反序列化 JSON

You could use the JavaScriptSerializer class (add reference to System.Web.Extensions ):您可以使用JavaScriptSerializer class (添加对System.Web.Extensions的引用):

using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);

A full example:一个完整的例子:

using System;
using System.Web.Script.Serialization;

public class MyDate
{
    public int year;
    public int month;
    public int day;
}

public class Lad
{
    public string firstName;
    public string lastName;
    public MyDate dateOfBirth;
}

class Program
{
    static void Main()
    {
        var obj = new Lad
        {
            firstName = "Markoff",
            lastName = "Chaney",
            dateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };
        var json = new JavaScriptSerializer().Serialize(obj);
        Console.WriteLine(json);
    }
}

Use Json.Net library, you can download it from Nuget Packet Manager.使用Json.Net库,您可以从 Nuget 数据包管理器下载它。

Serializing to Json String:序列化为 Json 字符串:

 var obj = new Lad
        {
            firstName = "Markoff",
            lastName = "Chaney",
            dateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };

var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

Deserializing to Object:反序列化为 Object:

var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Lad>(jsonString );

Use the DataContractJsonSerializer class: MSDN1 ,MSDN2 .使用DataContractJsonSerializer class: MSDN1 ,MSDN2

My example: HERE .我的例子:这里

It can also safely deserialize objects from a JSON string, unlike JavaScriptSerializer .JavaScriptSerializer不同,它还可以安全地从 JSON 字符串中反序列化对象。 But personally I still prefer Json.NET .但我个人还是更喜欢Json.NET

A new JSON serializer is available in the System.Text.Json namespace. System.Text.Json命名空间中提供了一个新的 JSON 序列化程序。 It's included in the .NET Core 3.0 shared framework and is in a NuGet package for projects that target .NET Standard or .NET Framework or .NET Core 2.x. It's included in the .NET Core 3.0 shared framework and is in a NuGet package for projects that target .NET Standard or .NET Framework or .NET Core 2.x.

Example code:示例代码:

using System;
using System.Text.Json;

public class MyDate
{
    public int year { get; set; }
    public int month { get; set; }
    public int day { get; set; }
}

public class Lad
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public MyDate DateOfBirth { get; set; }
}

class Program
{
    static void Main()
    {
        var lad = new Lad
        {
            FirstName = "Markoff",
            LastName = "Chaney",
            DateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };
        var json = JsonSerializer.Serialize(lad);
        Console.WriteLine(json);
    }
}

In this example the classes to be serialized have properties rather than fields;在此示例中,要序列化的类具有属性而不是字段; the System.Text.Json serializer currently doesn't serialize fields. System.Text.Json序列化程序当前不序列化字段。

Documentation:文档:

You can achieve this by using Newtonsoft.json.您可以通过使用 Newtonsoft.json 来实现此目的。 Install Newtonsoft.json from NuGet.从 NuGet 安装 Newtonsoft.json。 And then:接着:

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(obj);

Wooou: Really better using a JSON framework :) Wooou:使用 JSON 框架真的更好:)

Here is my example using Json.NET ( http://james.newtonking.com/json ):这是我使用 Json.NET 的示例( http://james.newtonking.com/json ):

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.IO;

namespace com.blogspot.jeanjmichel.jsontest.model
{
    public class Contact
    {
        private Int64 id;
        private String name;
        List<Address> addresses;

        public Int64 Id
        {
            set { this.id = value; }
            get { return this.id; }
        }

        public String Name
        {
            set { this.name = value; }
            get { return this.name; }
        }

        public List<Address> Addresses
        {
            set { this.addresses = value; }
            get { return this.addresses; }
        }

        public String ToJSONRepresentation()
        {
            StringBuilder sb = new StringBuilder();
            JsonWriter jw = new JsonTextWriter(new StringWriter(sb));

            jw.Formatting = Formatting.Indented;
            jw.WriteStartObject();
            jw.WritePropertyName("id");
            jw.WriteValue(this.Id);
            jw.WritePropertyName("name");
            jw.WriteValue(this.Name);

            jw.WritePropertyName("addresses");
            jw.WriteStartArray();

            int i;
            i = 0;

            for (i = 0; i < addresses.Count; i++)
            {
                jw.WriteStartObject();
                jw.WritePropertyName("id");
                jw.WriteValue(addresses[i].Id);
                jw.WritePropertyName("streetAddress");
                jw.WriteValue(addresses[i].StreetAddress);
                jw.WritePropertyName("complement");
                jw.WriteValue(addresses[i].Complement);
                jw.WritePropertyName("city");
                jw.WriteValue(addresses[i].City);
                jw.WritePropertyName("province");
                jw.WriteValue(addresses[i].Province);
                jw.WritePropertyName("country");
                jw.WriteValue(addresses[i].Country);
                jw.WritePropertyName("postalCode");
                jw.WriteValue(addresses[i].PostalCode);
                jw.WriteEndObject();
            }

            jw.WriteEndArray();

            jw.WriteEndObject();

            return sb.ToString();
        }

        public Contact()
        {
        }

        public Contact(Int64 id, String personName, List<Address> addresses)
        {
            this.id = id;
            this.name = personName;
            this.addresses = addresses;
        }

        public Contact(String JSONRepresentation)
        {
            //To do
        }
    }
}

The test:考试:

using System;
using System.Collections.Generic;
using com.blogspot.jeanjmichel.jsontest.model;

namespace com.blogspot.jeanjmichel.jsontest.main
{
    public class Program
    {
        static void Main(string[] args)
        {
            List<Address> addresses = new List<Address>();
            addresses.Add(new Address(1, "Rua Dr. Fernandes Coelho, 85", "15º andar", "São Paulo", "São Paulo", "Brazil", "05423040"));
            addresses.Add(new Address(2, "Avenida Senador Teotônio Vilela, 241", null, "São Paulo", "São Paulo", "Brazil", null));

            Contact contact = new Contact(1, "Ayrton Senna", addresses);

            Console.WriteLine(contact.ToJSONRepresentation());
            Console.ReadKey();
        }
    }
}

The result:结果:

{
  "id": 1,
  "name": "Ayrton Senna",
  "addresses": [
    {
      "id": 1,
      "streetAddress": "Rua Dr. Fernandes Coelho, 85",
      "complement": "15º andar",
      "city": "São Paulo",
      "province": "São Paulo",
      "country": "Brazil",
      "postalCode": "05423040"
    },
    {
      "id": 2,
      "streetAddress": "Avenida Senador Teotônio Vilela, 241",
      "complement": null,
      "city": "São Paulo",
      "province": "São Paulo",
      "country": "Brazil",
      "postalCode": null
    }
  ]
}

Now I will implement the constructor method that will receives a JSON string and populates the class' fields.现在我将实现构造函数方法,该方法将接收 JSON 字符串并填充类的字段。

If they are not very big, what's probably your case export it as JSON.如果它们不是很大,那么您的情况可能是将其导出为 JSON。

Also this makes it portable among all platforms.这也使得它可以在所有平台之间移植。

using Newtonsoft.Json;

[TestMethod]
public void ExportJson()
{
    double[,] b = new double[,]
        {
            { 110,  120,  130,  140, 150 },
            {1110, 1120, 1130, 1140, 1150},
            {1000,    1,   5,     9, 1000},
            {1110,    2,   6,    10, 1110},
            {1220,    3,   7,    11, 1220},
            {1330,    4,   8,    12, 1330}
        };

    string jsonStr = JsonConvert.SerializeObject(b);

    Console.WriteLine(jsonStr);

    string path = "X:\\Programming\\workspaceEclipse\\PyTutorials\\src\\tensorflow_tutorials\\export.txt";

    File.WriteAllText(path, jsonStr);
}

If you are in an ASP.NET MVC web controller it's as simple as:如果您在 ASP.NET MVC web controller 中,则非常简单:

string ladAsJson = Json(Lad);

Can't believe no one has mentioned this.不敢相信没有人提到这一点。

I would vote for ServiceStack's JSON Serializer:我会投票给 ServiceStack 的 JSON 串行器:

using ServiceStack;

string jsonString = new { FirstName = "James" }.ToJson();

It is also the fastest JSON serializer available for .NET: http://www.servicestack.net/benchmarks/它也是可用于 .NET 的最快的 JSON 串行器: http://www.servicestack.net/benchmarks/

Use these tools for generating a C# class, and then use this code to serialize your object:使用这些工具生成 C# class,然后使用此代码序列化您的 object:

 var json = new JavaScriptSerializer().Serialize(obj);

It is as easy as this (it works for dynamic objects as well (type object)):就这么简单(它也适用于动态对象(类型对象)):

string json = new
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(MYOBJECT);

Use the below code for converting XML to JSON.使用以下代码将 XML 转换为 JSON。

var json = new JavaScriptSerializer().Serialize(obj);

Another solution using System.Text.Json (.NET Core 3.0+, .NET 5) where an object is self-sufficient and doesn't expose all possible fields:使用System.Text.Json (.NET Core 3.0+, .NET 5) 的另一种解决方案,其中object 是自给自足的并且不会公开所有可能的字段:

A passing test:通过测试:

using NUnit.Framework;

namespace Intech.UnitTests
{
    public class UserTests
    {
        [Test]
        public void ConvertsItselfToJson()
        {
            var userName = "John";
            var user = new User(userName);

            var actual = user.ToJson();

            Assert.AreEqual($"{{\"Name\":\"{userName}\"}}", actual);
        }
    }
}

An implementation:一个实现:

using System.Text.Json;
using System.Collections.Generic;

namespace Intech
{
    public class User
    {
        private readonly string Name;

        public User(string name)
        {
            this.Name = name;
        }

        public string ToJson()
        {
            var params = new Dictionary<string, string>{{"Name", Name}};
            return JsonSerializer.Serialize(params);
        }
    }
}

Here is another solution using Cinchoo ETL - an open source library这是另一个使用Cinchoo ETL的解决方案 - 一个开源库

public class MyDate
{
    public int year { get; set; }
    public int month { get; set; }
    public int day { get; set; }
}

public class Lad
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public MyDate dateOfBirth { get; set; }
}

static void ToJsonString()
{
    var obj = new Lad
    {
        firstName = "Tom",
        lastName = "Smith",
        dateOfBirth = new MyDate
        {
            year = 1901,
            month = 4,
            day = 30
        }
    };
    var json = ChoJSONWriter.Serialize<Lad>(obj);

    Console.WriteLine(json);
}

Output: Output:

{
  "firstName": "Tom",
  "lastName": "Smith",
  "dateOfBirth": {
    "year": 1901,
    "month": 4,
    "day": 30
  }
}

Disclaimer: I'm the author of this library.免责声明:我是这个库的作者。

Serializer串行器

 public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
        var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite, new JsonSerializerSettings
        {
            Formatting = Formatting.Indented,
        });
        using (var writer = new StreamWriter(filePath, append))
        {
            writer.Write(contentsToWriteToFile);
        }
}

Object Object

namespace MyConfig
{
    public class AppConfigurationSettings
    {
        public AppConfigurationSettings()
        {
            /* initialize the object if you want to output a new document
             * for use as a template or default settings possibly when 
             * an app is started.
             */
            if (AppSettings == null) { AppSettings=new AppSettings();}
        }

        public AppSettings AppSettings { get; set; }
    }

    public class AppSettings
    {
        public bool DebugMode { get; set; } = false;
    }
}

Implementation执行

var jsonObject = new AppConfigurationSettings();
WriteToJsonFile<AppConfigurationSettings>(file.FullName, jsonObject);

Output Output

{
  "AppSettings": {
    "DebugMode": false
  }
}

In your Lad model class, add an override to the ToString() method that returns a JSON string version of your Lad object.在您的小伙子 model class 中,向ToString()方法添加一个覆盖,该方法返回您的小伙子 JSON 字符串版本的 JSON 字符串版本。
Note: you will need to import System.Text.Json ;注意:您需要导入System.Text.Json

using System.Text.Json;

class MyDate
{
    int year, month, day;
}

class Lad
{
    public string firstName { get; set; };
    public string lastName { get; set; };
    public MyDate dateOfBirth { get; set; };
    public override string ToString() => JsonSerializer.Serialize<Lad>(this);
}

There is this really nifty utility right here: http://csharp2json.io/这里有一个非常漂亮的实用程序: http://csharp2json.io/

Take care to create your class with the right attribute too:请注意创建具有正确属性的 class :

Create this class with <Serializable> attribute as per the example C# example followed by vb.net exmpale根据示例 C# 示例,后跟 vb.net 示例,创建具有 <Serializable> 属性的此 class

C# C#

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Script.Serialization;
namespace Samples
{
[Serializable()]
public class Customer
{


    private int _idcustomer;
    public int IDCustomer {
        get { return _idcustomer; }
        set { _idcustomer = value; }
    }


    private System.DateTime _RegistrationDate;
    public System.DateTime RegistrationDate {
        get { return _RegistrationDate; }
        set { _RegistrationDate = value; }
    }


    private string _Name;
    public string Name {
        get { return _Name; }
        set { _Name = value; }
    }


    private string _Surname;
    public string Surname {
        get { return _Surname; }
        set { _Surname = value; }
    }
}


[Serializable()]
public class Product
{


    private int _ProductID;
    public int ProductID {
        get { return _ProductID; }
        set { _ProductID = value; }
    }


    private string _ProductName;
    public string ProductName {
        get { return _ProductName; }
        set { _ProductName = value; }
    }


    private int _Price;
    public int Price {
        get { return _Price; }
        set { _Price = value; }
    }


    private bool _inStock;
    public bool inStock {
        get { return _inStock; }
        set { _inStock = value; }
    }
}


[Serializable()]
public class Order
{


    private int _OrderId;
    public int OrderID {
        get { return _OrderId; }
        set { _OrderId = value; }
    }


    private int _customerID;
    public int CustomerID {
        get { return _customerID; }
        set { _customerID = value; }
    }


    private List<Product> _ProductsList;
    public List<Product> ProductsList {
        get { return _ProductsList; }
        set { _ProductsList = value; }
    }


    private System.DateTime _PurchaseDate;
    public System.DateTime PurchaseDate {
        get { return _PurchaseDate; }
        set { _PurchaseDate = value; }
    }


    private string _PaymentMethod;
    public string PaymentMethod {
        get { return _PaymentMethod; }
        set { _PaymentMethod = value; }
    }

    public string ToJson()
    {
        string json = string.Empty;
        JavaScriptSerializer js = new JavaScriptSerializer();
        json = js.Serialize(this);
        js = null;
        return json;
    }

}

}

VBNET EXAMPLE VBNET 示例

Imports System
Imports System.Web
Imports System.Web.Script.Serialization
Namespace Samples
<Serializable()>
Public Class Customer

    Private _idcustomer As Integer

    Public Property IDCustomer() As Integer
        Get
            Return _idcustomer
        End Get
        Set(ByVal value As Integer)
            _idcustomer = value
        End Set
    End Property

    Private _RegistrationDate As Date

    Public Property RegistrationDate() As Date
        Get
            Return _RegistrationDate
        End Get
        Set(ByVal value As Date)
            _RegistrationDate = value
        End Set
    End Property

    Private _Name As String

    Public Property Name() As String
        Get
            Return _Name
        End Get
        Set(ByVal value As String)
            _Name = value
        End Set
    End Property

    Private _Surname As String

    Public Property Surname() As String
        Get
            Return _Surname
        End Get
        Set(ByVal value As String)
            _Surname = value
        End Set
    End Property
End Class


<Serializable()>
Public Class Product

    Private _ProductID As Integer

    Public Property ProductID() As Integer
        Get
            Return _ProductID
        End Get
        Set(ByVal value As Integer)
            _ProductID = value
        End Set
    End Property

    Private _ProductName As String

    Public Property ProductName() As String
        Get
            Return _ProductName
        End Get
        Set(ByVal value As String)
            _ProductName = value
        End Set
    End Property

    Private _Price As Integer

    Public Property Price() As Integer
        Get
            Return _Price
        End Get
        Set(ByVal value As Integer)
            _Price = value
        End Set
    End Property

    Private _inStock As Boolean

    Public Property inStock() As Boolean
        Get
            Return _inStock
        End Get
        Set(ByVal value As Boolean)
            _inStock = value
        End Set
    End Property
End Class


<Serializable>
Public Class Order

    Private _OrderId As Integer

    Public Property OrderID() As Integer
        Get
            Return _OrderId
        End Get
        Set(ByVal value As Integer)
            _OrderId = value
        End Set
    End Property

    Private _customerID As Integer

    Public Property CustomerID() As Integer
        Get
            Return _customerID
        End Get
        Set(ByVal value As Integer)
            _customerID = value
        End Set
    End Property

    Private _ProductsList As List(Of Product)

    Public Property ProductsList() As List(Of Product)
        Get
            Return _ProductsList
        End Get
        Set(ByVal value As List(Of Product))
            _ProductsList = value
        End Set
    End Property

    Private _PurchaseDate As Date

    Public Property PurchaseDate() As Date
        Get
            Return _PurchaseDate
        End Get
        Set(ByVal value As Date)
            _PurchaseDate = value
        End Set
    End Property

    Private _PaymentMethod As String

    Public Property PaymentMethod() As String
        Get
            Return _PaymentMethod
        End Get
        Set(ByVal value As String)
            _PaymentMethod = value
        End Set
    End Property

    Public Function ToJson() As String
        Dim json As String = String.Empty
        Dim js As New JavaScriptSerializer
        json = js.Serialize(Me)
        js = Nothing
        Return json
    End Function

End Class

End Namespace结束命名空间

The second step is to create a simple test data like this:第二步是创建一个简单的测试数据,如下所示:

C# C#

  void Main() {
    List<Samples.Product> ListProducts = new List<Samples.Product>();
    ListProducts.Add(new Samples.Product(), With, {.inStock=False,.Price=10, .ProductID=1,.ProductName=BookOne);
    ListProducts.Add(new Samples.Product(), With, {.inStock=False,. Price=10, .ProductID=2, .ProductName=Hotels California);
    ListProducts.Add(new Samples.Product(), With, {.inStock=False,.Price=10,.ProductID=3,.ProductName=Cbr);
    ListProducts.Add(new Samples.Product(), With, {.inStock=False,.Price=10,.ProductID=4,.ProductName=Mustang);
    ListProducts.Add(new Samples.Product(), With, {.inStock=False,.Price=10, .ProductID=15,.ProductName=Anything);
    ListProducts.Add(new Samples.Product(), With, {.inStock=False,.Price=10,.ProductID=38,.ProductName=Monster Truck);
    Samples.Customer Customer = new Samples.Customer();
    // With...
    Customer.IDCustomer = 1;
    Customer.Name = "Customer1";
    Customer.RegistrationDate = Now;
    Customer.Surname = "SurnameCustomer";
    Samples.Order Order = new Samples.Order();
    // With...
    Order.CustomerID = Customer.IDCustomer;
    Order.OrderID = 1;
    Order.PaymentMethod = "PayPal";
    Order.ProductsList = ListProducts;
    Order.PurchaseDate = Now;
    Console.WriteLine(Order.ToJson);
    Console.ReadLine();
}

VB.NET VB.NET

Sub Main()
    Dim ListProducts As New List(Of Samples.Product)

    ListProducts.Add(New Samples.Product With {.inStock = False, .Price = 10,
                     .ProductID = 1, .ProductName = "BookOne"})
    ListProducts.Add(New Samples.Product With {.inStock = False, .Price = 10,
                     .ProductID = 2, .ProductName = "Hotels California"})
    ListProducts.Add(New Samples.Product With {.inStock = False, .Price = 10,
                     .ProductID = 3, .ProductName = "Cbr"})
    ListProducts.Add(New Samples.Product With {.inStock = False, .Price = 10,
                     .ProductID = 4, .ProductName = "Mustang"})
    ListProducts.Add(New Samples.Product With {.inStock = False, .Price = 10,
                     .ProductID = 15, .ProductName = "Anything"})
    ListProducts.Add(New Samples.Product With {.inStock = False, .Price = 10,
                     .ProductID = 38, .ProductName = "Monster Truck"})

    Dim Customer As New Samples.Customer
    With {.IDCustomer = 1, .Name = "Customer1",.RegistrationDate = Now, .Surname  ="SurnameCustomer"}

    Dim Order As New Samples.Order With {
        .CustomerID = Customer.IDCustomer,
        .OrderID =       1,
        .PaymentMethod = "PayPal",
        .ProductsList = ListProducts,
        .PurchaseDate = Now
    }
    Console.WriteLine(Order.ToJson)
    Console.ReadLine()
End Sub

And this is the final result:这是最终的结果:

{"OrderID":1,"CustomerID":1,"ProductsList":[{"ProductID":1,"ProductName":"BookOn
 e","Price":10,"inStock":false},{"ProductID":2,"ProductName":"Hotels California",
 "Price":10,"inStock":false},{"ProductID":3,"ProductName":"Cbr","Price":10,"inSto
 ck":false},{"ProductID":4,"ProductName":"Mustang","Price":10,"inStock":false},{"
 ProductID":15,"ProductName":"Anything","Price":10,"inStock":false},{"ProductID":
 38,"ProductName":"Monster Truck","Price":10,"inStock":false}],"PurchaseDate":"\/
 Date(1396642206155)\/","PaymentMethod":"PayPal"}

Remember to add a reference to system.web.extension.dll in order to achive your goal.请记住添加对 system.web.extension.dll 的引用以实现您的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM