c# 에서 객체를 json 문자열로 바꾸려면 System.Text.Json.JsonSerializer 를 사용하면 된다.

using System.Text.Json;

public class ObjectA
{
    public int a { get; set; }
    public int b { get; set; }
    public int c { get; set; }
}

public class JsonTest
{
    public static void Main()
    {
        var objA = new ObjectA() { a = 1, b = 2, c = 3};
        
        var jsonStr = System.Text.Json.JsonSerializer.Serialize(objA);

        Console.WriteLine(jsonStr);
    }
 }

 

$ JsonTest.exe
{"a":1,"b":2,"c":3}

위와 같이 json 문자열로 변환되기를 원하는 문자열을 property 로 선언하고 JsonSerializer.Serialize 함수를 호출하면 된다.

using Newtonsoft.Json;
using System.Text.Json;

public class ObjectA
{
    public int a { get; set; }
    public int b { get; set; }
    public int c { get; set; }

    public int d;
}

public class JsonTest
{
    public static void Main()
    {
        var objA = new ObjectA() { a = 1, b = 2, c = 3, d = 4 };
        
        var jsonStr = System.Text.Json.JsonSerializer.Serialize(objA);

        Console.WriteLine(jsonStr);

        var jsonStr2 = JsonConvert.SerializeObject(objA);
        Console.WriteLine(jsonStr2);
    }
}
$ JsonTest.exe
{"a":1,"b":2,"c":3}
{"d":4,"a":1,"b":2,"c":3}

하지만 위와 같이 property 선언되지 않은 멤버들은 json 문자열로 출력되지 않는다. property 선언되지 않은 d 까지  json 문자열로 변환되길 바란다면 Newtonsoft.Json 을 이용하자. JsonConvert.SerializeObject 함수를 이용하면 된다.

참고로 protobuf descriptor 가 없는 경우에 System.Text.Json.JsonSerializer 를 이용한다면 json 으로 변환되지 않았다.

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

 

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...

stackoverflow.com

 

728x90

+ Recent posts