Comment transformer un objet C# en chaîne JSON in.NET Je ne sais pas.

j'ai des classes comme celles-ci:

class MyDate
{
    int year, month, day;
}

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

et je voudrais transformer un objet Lad en chaîne JSON comme ceci:

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

(sans le formatage). J'ai trouvé ce lien , mais il utilise un espace de nom qui n'est pas dans .NET 4. J'ai aussi entendu parler de JSON.NET , mais leur site semble être en panne pour le moment, et je ne suis pas désireux d'utiliser des fichiers DLL externes. Il existe d'autres options à part créer manuellement un rédacteur de string JSON?

650
demandé sur Liam 2011-06-01 16:59:21

14 réponses

vous pouvez utiliser la classe JavaScriptSerializer (ajouter une référence à System.Web.Extensions ):

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

un exemple complet:

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);
    }
}
716
répondu Darin Dimitrov 2015-10-12 19:33:27

puisque nous aimons tous les doublures

... celui-ci dépend du paquet NuGet Newtonsoft, qui est populaire et meilleur que le serializer par défaut.

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

de la Documentation: la Sérialisation et la Désérialisation JSON

692
répondu willsteel 2015-01-30 22:09:58

utiliser la classe DataContractJsonSerializer : MSDN1 , MSDN2 .

mon exemple: ici .

il peut aussi désérialiser en toute sécurité des objets à partir d'une chaîne JSON, contrairement à JavaScriptSerializer . Mais personnellement je préfère encore Json.NET .

51
répondu Edgar 2016-07-15 14:09:04

utiliser Json.Net bibliothèque , vous pouvez le télécharger à partir de Nuget Packet Manager.

la Sérialisation Json Chaîne:

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

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

désérialisation de L'objet:

var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Lad>(jsonString );
40
répondu Gokulan P H 2017-06-21 08:15:20

Wooou! Vraiment mieux à l'aide d'un JSON cadre :)

Voici mon exemple en utilisant 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
        }
    }
}

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

le résultat:

{
  "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
    }
  ]
}

maintenant je vais implémenter la méthode du constructeur qui recevra une chaîne JSON et peuplera les champs de la classe.

20
répondu Jean J. Michel 2015-05-07 15:23:45

si vous êtes dans un ASP.NET MVC Web controller c'est aussi simple que:

string ladAsJson = Json(Lad);

Je n'arrive pas à croire que personne ne l'ait mentionné.

4
répondu micahhoover 2016-09-16 15:53:46

si elles ne sont pas très grandes, ce qui est probablement votre cas l'exporter comme Json. Aussi cela rend portable parmi toutes les plateformes

 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);
    }
3
répondu user8426627 2018-01-28 16:00:31

je voterais pour ServiceStack du Sérialiseur JSON:

using ServiceStack.Text

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

il est également le plus rapide serializer JSON disponible pour. NET: http://www.servicestack.net/benchmarks /

2
répondu James 2013-10-02 13:39:59

utilisez le code ci-dessous pour convertir XML en JSON.

var json = new JavaScriptSerializer().Serialize(obj);
2
répondu Hithesh 2014-11-09 09:46:15

aussi simple que cela, fonctionne aussi bien pour les objets dynamiques (taper objet):

string json = new
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(MYOBJECT);
2
répondu MarzSocks 2015-04-27 06:24:40

Utiliser cette outils pour générer de classe C#, puis utiliser ce code pour sérialiser l'objet de votre

 var json = new JavaScriptSerializer().Serialize(obj);
2
répondu Artem Polischuk 2018-08-17 15:14:58

Sérialiseur

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

objet

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

mise en Œuvre

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

Sortie

{
  "AppSettings": {
    "DebugMode": false
  }
}
0
répondu wchoward 2016-02-03 19:31:40

il y a cette très belle utilité ici: http://csharp2json.io/

0
répondu jallen 2018-04-24 18:03:27

prenez soin de créer votre classe avec l'attribut droit aussi:

créer cette classe avec l'attribut < Serializable> suivant l'exemple c # exemple suivi de vb.net exmpale

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

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

Fin De L'Espace De Noms

la deuxième étape est de créer des données de test simples comme ceci:

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

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

Et voici le résultat final:

{"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"}

N'oubliez pas d'ajouter une référence au système.Web.extension.dll pour atteindre votre but.

-7
répondu makemoney2010 2016-06-05 12:54:40