>  기사  >  백엔드 개발  >  객체를 JSON C#으로 변환

객체를 JSON C#으로 변환

WBOY
WBOY원래의
2024-09-03 15:27:30236검색

객체를 저장하거나 나중에 검색하려면 객체의 현재 상태를 얻어야 하며 코딩 시 이를 고려해야 하며, 객체의 상태를 출력하기 위해 사용자 정의 코드를 추가하는 것을 C#에서는 객체를 Json 문자열로 변환한다고 합니다. 그리고 객체의 종류에 대해 우리가 알고 있는 지식의 종류에 따라 객체의 모든 속성에 대해 코딩이 이루어져야 합니다. 객체 유형의 정의가 변경되면 코드도 변경되어야 하며 Newtonsoft의 Json.NET 라이브러리를 사용하여 객체를 C#의 Json으로 변환합니다. 이는 코드를 사용하여 객체 문자열의 완전한 표현을 제공합니다. 한 줄로 작성되었습니다.

구문:

Variable variable_name =Newtonsoft.Json.JsonConvert.SerializeObject(parameter);

C#에서 개체를 JSON 문자열로 변환

  • C#에서 객체를 Json 문자열로 변환하는 것만으로 객체 직렬화가 NewtonsoftJson을 사용하여 어떻게 수행되는지 살펴보겠습니다.
  • 객체를 Json 문자열로 변환하는 첫 번째 단계로 새로운 Visual Studio 프로젝트가 생성됩니다.
  • NewtonsoftJson은 Nuget을 사용하여 설치됩니다.
  • 직렬화를 위해 객체를 Json 문자열로 변환하는 예제 클래스가 생성되었습니다.
  • 그런 다음 개체를 Json 문자열로 변환하거나 C#에서 개체를 직렬화하는 메서드가 생성됩니다.
  • 마지막으로 C#에서 객체를 직렬화하는 프로그램이 실행됩니다. 이는 객체를 C#에서 Json 문자열로 변환하는 것뿐입니다.

객체를 JSON C#으로 변환하는 예

다음은 언급된 예입니다.

예시 #1

객체를 Json 문자열로 변환하는 방법을 보여주는 C# 프로그램. 이는 C#의 객체 직렬화에 불과합니다.

코드:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
//a namespace called Serial is defined
namespace Serial
{
//a class called Data is defined
public class Data
{
//a string variable is defined which can be set or retrieved using get or set method
public string Name1 { get; set; }
//a list is defined which can be set or retrieved using get or set method
public List<int> Ids { get; set; }
//a method called Print is defined in which the name and the list is printed
public void Print()
{
Console.WriteLine("The Name is: " + Name1);
Console.WriteLine("The Identifiers used are: " + string.Join<int>(",", Ids));
Console.WriteLine();
Console.WriteLine();
}
}
//a class called check is defined
public class Check
{
//a file path is defined and stored in a string variable
const string fPath = @"d:\ex.txt";
//Serialize method is defined in which instances of Json writer and Stream writer classes are defined to write into the file
public static void Serialize(object ob)
{
varserialise = new JsonSerializer();
using (var ns = new StreamWriter(fPath))
using (JsonWriter writer1 = new JsonTextWriter(ns))
{
serialise.Serialize(writer1, ob);
}
}
//Deserialize method is defined in which instances of Json text reader and Stream reader classes are defined to read from the file
public static object Deserialize(string pa)
{
varserialise = new JsonSerializer();
using (var ns = new StreamReader(pa))
using (var reader1 = new JsonTextReader(ns))
{
return serialise.Deserialize(reader1);
}
}
//main method is called
public static void Main(string[] args)
{
vardat = new Data
{
Name1 = "ShobhaShivakumar",
Ids = new List<int>{ 10, 20, 30, 40 }
};
Console.WriteLine("Before serialization of the objects, the list of the objects are:");
Console.WriteLine("-------------------------------------------------------------------");
Console.WriteLine();
dat.Print();
Serialize(dat);
vardeserialise = Deserialize(fPath);
Console.WriteLine("After de-serialization of the object, the objects are:");
Console.WriteLine("---------------------------");
Console.WriteLine();
Console.WriteLine(deserialise);
}
}
}

출력:

객체를 JSON C#으로 변환

설명:

  • 위 프로그램에는 Serial이라는 네임스페이스가 정의되어 있습니다. 그런 다음 Data라는 클래스가 정의됩니다. 그런 다음 get 또는 set 메소드를 사용하여 설정하거나 검색할 수 있는 문자열 변수가 정의됩니다. 그런 다음 get 또는 set 메소드를 사용하여 설정하거나 검색할 수 있는 목록이 정의됩니다. 그런 다음 이름과 목록이 인쇄되는 Print라는 메서드가 정의됩니다. 그런 다음 check라는 클래스가 정의됩니다. 그런 다음 파일 경로가 정의되어 문자열 변수에 저장됩니다.
  • 그런 다음 Jsonwriter 및 Streamwriter 클래스의 인스턴스가 파일에 쓰도록 정의되는 Serialize 메서드가 정의됩니다. 그런 다음 Jsontext 리더 및 Streamreader 클래스의 인스턴스가 파일에서 읽도록 정의되는 De serialize 메서드가 정의됩니다. 그런 다음 객체 직렬화 전에 출력을 표시하는 메서드를 호출하는 기본 메서드가 호출됩니다.

예시 #2

프로그램에서 수동 직렬화와 Json 직렬화의 차이점을 보여주는 C# 프로그램

코드:

using System;
using System.Text;
using System.Collections.Generic;
//a class called check is defined
public class Check
{
//main method is called
public static void Main()
{
//an instance of the Create request1 class and string builder class is created
var request = CreateRequest1();
var output1 = new StringBuilder();
//Since we are using manual serialization here, we have to output the properties manually
output1.AppendFormat("The unique ID is: {0}\n", request.UniqueID);
output1.AppendFormat("The unique Name is: {0}\n", request.UniqueName);
output1.AppendFormat("The unique Surname is: {0}\n", request.UniqueSurname);
output1.AppendFormat("The Last Sign In is: {0}\n", request.UniqueLastSignIn);
//We need to make use of for loop to output the nested attributes in case of manual serialization
output1.AppendFormat("The Attributes are:\n");
foreach (varsh in request.UniqueAttributes)
{
output1.AppendFormat("    {0}\n", sh);
}
Console.WriteLine(output1.ToString());
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(request);
//We are using Json serialization to improve the readability
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(request, Newtonsoft.Json.Formatting.Indented));
}
//a method called Create request1 is defined
public static Req CreateRequest1()
{
return new Req
{
UniqueID = 10,
UniqueName = "Shobha",
UniqueSurname = "Shivakumar",
UniqueLastSignIn = DateTime.Now,
UniqueAttributes = new List<string>
{
"Beautiful",
"Tall",
"Intelligent",
"Wise",
}
};
}
//a class called req is created
public class Req
{
public intUniqueID {get;set;}
public string UniqueName {get;set;}
public string UniqueSurname {get;set;}
public DateTimeUniqueLastSignIn {get;set;}
public List<string>UniqueAttributes {get;set;}
}
}

출력:

객체를 JSON C#으로 변환

설명:

  • 위 프로그램에는 check라는 클래스가 정의되어 있습니다. 그런 다음 기본 메소드가 호출됩니다. 그런 다음 Create request1 클래스 및 문자열 빌더 클래스의 인스턴스가 생성됩니다. 그런 다음 여기서는 수동 직렬화를 사용하므로 속성을 수동으로 출력해야 합니다. 그런 다음 수동 직렬화의 경우처럼 for 루프를 사용하여 중첩된 속성을 출력해야 합니다.
  • 그런 다음 가독성을 높이기 위해 Json 직렬화를 사용합니다. 그런 다음 Create request1이라는 메서드가 정의됩니다. 그런 다음 get 또는 set 메소드를 사용하여 모든 속성을 설정하고 검색하는 req라는 클래스가 생성됩니다.

위 내용은 객체를 JSON C#으로 변환의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:C# 조건자다음 기사:C# 조건자