sourcecode

에서 C# 개체를 JSON 문자열로 변환하려면 어떻게 해야 합니까?인터넷?

codebag 2023. 3. 29. 21:27
반응형

에서 C# 개체를 JSON 문자열로 변환하려면 어떻게 해야 합니까?인터넷?

다음과 같은 수업이 있습니다.

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

(포맷 없음).링크를 찾았는데 없는 네임스페이스를 사용합니다. 4. JSON도 들었어요.NET, 하지만 지금은 사이트가 다운된 것 같아서 외부 DLL 파일 사용에는 관심이 없습니다.

JSON 문자열 작성기를 수동으로 작성하는 것 외에 다른 옵션이 있습니까?

우리 모두 외줄타기를 좋아하니까

이 패키지는 뉴턴소프트 NuGet 패키지에 의존합니다.이 패키지는 일반 시리얼라이저보다 우수합니다.

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

문서:JSON 시리얼화 및 역직렬화

부디 참고하세요

Microsoft는 JavaScriptSerializer를 사용하지 않을 것을 권장합니다.

문서 페이지의 헤더를 참조해 주세요.

.NET Framework 4.7.2 이후 버전의 경우 시스템의 API를 사용합니다.직렬화 및 직렬화를 위한 Text.Json 네임스페이스.의 이전 버전의 경우.NET Framework, Newtonsoft를 사용합니다.제이슨.


원답:

클래스를 사용할 수 있습니다(참조 항목 추가).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);
    }
}

Json을 사용합니다. 라이브러리는 Nuget Packet Manager에서 다운로드할 수 있습니다.

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

개체로 역직렬화:

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

를 사용합니다.DataContractJsonSerializer클래스: MSDN1, MSDN2

예: 여기.

또한 JSON 문자열에서 개체를 안전하게 역직렬화할 수 있습니다.JavaScriptSerializer하지만 개인적으로는 여전히 Json을 선호합니다.네트워크

새로운 JSON 시리얼라이저는System.Text.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.Jsonserializer는 현재 필드를 직렬화하지 않습니다.

문서:

이를 위해서는 Newtonsoft.json을 사용합니다.NuGet에서 Newtonsoft.json을 설치합니다.그 후:

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(obj);

Wooou! 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 문자열을 수신하여 클래스의 필드를 채우는 컨스트럭터 메서드를 구현합니다.

그다지 크지 않은 경우, JSON으로 수출하는 것은 어떤 경우입니까?

또한 모든 플랫폼에서 휴대할 수 있습니다.

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

ASP에 있는 경우.NET MVC Web 컨트롤러는 다음과 같이 심플합니다.

string ladAsJson = Json(Lad);

아무도 이걸 언급하지 않았다니 믿을 수 없다.

ServiceStack의 JSON Serializer에 투표합니다.

using ServiceStack;

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

또, 에서 이용 가능한 가장 빠른 JSON 시리얼라이저이기도 합니다.NET: http://www.servicestack.net/benchmarks/

을 사용한 다른 System.Text.Json(.NET Core 3.0+) 이 경우 오브젝트는 자급자족하며 가능한 모든 필드가 표시되지 않습니다.

합격 테스트:

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

구현:

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

Lad 모델 클래스에서 Lad 객체의 JSON 문자열 버전을 반환하는 ToString() 메서드에 오버라이드를 추가합니다.
주의: 시스템을 Import해야 합니다.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);
}

이것은 다음과 같이 간단합니다(동적인 오브젝트(타입 오브젝트)에서도 동작합니다).

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

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

출력:

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

면책사항:제가 이 도서관의 저자입니다.

시리얼라이저

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

물건

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

실행

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

산출량

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

언급URL : https://stackoverflow.com/questions/6201529/how-do-i-turn-a-c-sharp-object-into-a-json-string-in-net

반응형