나는 이런 수업을 가지고 있습니다 :
class MyDate
{
    int year, month, day;
}
class Lad
{
    string firstName;
    string lastName;
    MyDate dateOfBirth;
}
그리고 Lad객체를 다음 과 같이 JSON 문자열 로 바꾸고 싶습니다.
{
    "firstName":"Markoff",
    "lastName":"Chaney",
    "dateOfBirth":
    {
        "year":"1901",
        "month":"4",
        "day":"30"
    }
}
(포맷없이). 이 링크를 찾았 지만 .NET 4에 없는 네임 스페이스를 사용합니다 . JSON.NET에 대해서도 들었습니다. 사이트가 다운 된 것 같습니다. 외부 DLL 파일을 사용하고 싶지 않습니다.
JSON 문자열 작성기를 수동으로 만드는 것 외에 다른 옵션이 있습니까?
답변
JavaScriptSerializer클래스를 사용할 수 있습니다 (에 참조 추가 System.Web.Extensions).
using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);
전체 예 :
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);
    }
}
답변
우리 모두는 하나의 라이너를 사랑하기 때문에
… 이것은 Newtonsoft NuGet 패키지에 의존하는데, 이것은 기본 시리얼 라이저보다 널리 사용됩니다.
Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})
설명서 : JSON 직렬화 및 역 직렬화
답변
Json.Net 사용 라이브러리를 하면 Nuget Packet Manager에서 다운로드 할 수 있습니다.
Json String으로 직렬화 :
 var obj = new Lad
        {
            firstName = "Markoff",
            lastName = "Chaney",
            dateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
객체를 역 직렬화 :
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Lad>(jsonString );
답변
다음 DataContractJsonSerializer클래스를 사용하십시오 . MSDN1 , MSDN2 .
나의 예 : 여기 .
와 달리 JSON 문자열에서 객체를 안전하게 역 직렬화 할 수도 있습니다 JavaScriptSerializer. 그러나 개인적으로 나는 여전히 Json.NET을 선호 합니다 .
답변
Newtonsoft.json을 사용하여이를 달성 할 수 있습니다. NuGet에서 Newtonsoft.json을 설치하십시오. 그리고:
using Newtonsoft.Json;
var jsonString = JsonConvert.SerializeObject(obj);
답변
우우! 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
        }
    }
}
시험:
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();
        }
    }
}
결과:
{
  "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
    }
  ]
}
이제 JSON 문자열을 받고 클래스의 필드를 채우는 생성자 메서드를 구현하겠습니다.
답변
System.Text.Json네임 스페이스 에서 새로운 JSON 시리얼 라이저를 사용할 수 있습니다 . .NET Core 3.0 공유 프레임 워크에 포함되어 있으며 NuGet 패키지에 있습니다. .NET Standard 또는 .NET Framework 또는 .NET Core 2.x를 대상으로하는 프로젝트를위한 에 있습니다.
예제 코드 :
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);
    }
}
이 예제에서 직렬화 할 클래스에는 필드가 아닌 속성이 있습니다. 그만큼System.Text.Json시리얼 라이저는 현재 없습니다 직렬화 필드를한다.
선적 서류 비치:
