programing

코드에 JSON 문자열 값을 어떻게 쓰나요?

easyjava 2023. 3. 15. 20:00
반응형

코드에 JSON 문자열 값을 어떻게 쓰나요?

다음 문자열을 String 변수에 저장하려고 합니다.

{"Id":123", "Date Of Registration":2012-10-21T00:00:00+05:30", 상태:0}

이것은 내가 사용하는 코드이다.

String str="{"Id":"123","DateOfRegistration":"2012-10-21T00:00:00+05:30","Status":0}";

에러가 발생하고 있습니다.

이렇게 해야 돼

String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";


참고하시기 바랍니다.
msdn에서도 :)

Short Notation  UTF-16 character    Description
\'  \u0027  allow to enter a ' in a character literal, e.g. '\''
\"  \u0022  allow to enter a " in a string literal, e.g. "this is the double quote (\") character"
\\  \u005c  allow to enter a \ character in a character or string literal, e.g. '\\' or "this is the backslash (\\) character"
\0  \u0000  allow to enter the character with code 0
\a  \u0007  alarm (usually the HW beep)
\b  \u0008  back-space
\f  \u000c  form-feed (next page)
\n  \u000a  line-feed (next line)
\r  \u000d  carriage-return (move to the beginning of the line)
\t  \u0009  (horizontal-) tab
\v  \u000b  vertical-tab

C# 10 이하

저는 이것을 선호합니다. 문자열에 따옴표가 하나 들어가지 않도록 하세요.

 var str = "{'Id':'123','DateOfRegistration':'2012-10-21T00:00:00+05:30','Status':0}"
              .Replace("'", "\"");

C# 11 이상

아직 프리뷰 모드입니다만, json을 3중 따옴표 쌍 안에 넣기만 하면 됩니다.「 。

var str = """
    {
        "Id": "123",
        "DateOfRegistration": "2012-10-21T00:00:00+05:30",
        "Status": 0
    }
""";

sudhAnsu63의 답변을 정리하면 다음과 같습니다.

.NET Core 사용 시:

string str = JsonSerializer.Serialize(
  new {    
    Id = 2,
    DateOfRegistration = "2012-10-21T00:00:00+05:30",
    Status = 0
  }
);

Json이랑.네트워크:

string str = JsonConvert.SerializeObject(
  new {    
    Id = 2,
    DateOfRegistration = "2012-10-21T00:00:00+05:30",
    Status = 0
  }
);

를 인스턴스화할 필요는 없습니다.dynamic ExpandoObject.

Expando 객체 또는 XElement를 사용하여 이러한 복잡한 JSON을 작성한 후 직렬화하는 방법도 있습니다.

https://blogs.msdn.microsoft.com/csharpfaq/2009/09/30/dynamic-in-c-4-0-introducing-the-expandoobject/

dynamic contact = new ExpandoObject
{    
    Name = "Patrick Hines",
    Phone = "206-555-0144",
    Address = new ExpandoObject
    {    
        Street = "123 Main St",
        City = "Mercer Island",
        State = "WA",    
        Postal = "68402"
    }
};

//Serialize to get Json string using NewtonSoft.JSON
string Json = JsonConvert.SerializeObject(contact);

문자 그대로의 문자열 리터럴 포함(@"...") 큰따옴표를 " 대신 큰따옴표 쌍으로 바꾸면 인라인 다중행 json을 쓸 수 있습니다.예:

string str = @"
{
    ""Id"": ""123"",
    ""DateOfRegistration"": ""2012-10-21T00:00:00+05:30"",
    ""Status"": 0
}";

문자열 내의 따옴표는 다음과 같이 이스케이프해야 합니다.

String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";

C# 11은 Raw string literals라는 이름의 새로운 기능을 도입했습니다.JSON과의 작업이 매우 쉬워집니다.문자열은 1자가 아니라 3자의 큰따옴표로 묶습니다( ).""")의 마커:

string str = """{"Id":"123","DateOfRegistration":"2012-10-21T00:00:00+05:30","Status":0}""";

관련 유튜브 비디오: Nick Chapsas:C# 11의 현악기가 많이 좋아졌어요

다음과 같이 내부 인용구를 피해야 합니다.

String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";

틀에 박힌 사고방법은 JSON을 base64로 인코딩하여 한 줄의 문자열 값으로 Import할 수 있도록 했습니다.

이렇게 하면 동적 객체나 이스케이프 문자를 수동으로 쓸 필요 없이 줄 서식이 유지됩니다.형식은 텍스트 파일에서 JSON을 읽는 것과 동일합니다.

var base64 = "eyJJZCI6IjEyMyIsIkRhdGVPZlJlZ2lzdHJhdGlvbiI6IjIwMTItMTAtMjFUMDA6MDA6MDArMDU6MzAiLCJTdGF0dXMiOjB9";
byte[] data = Convert.FromBase64String(base64);
string json = Encoding.UTF8.GetString(data);

//using the JSON text
var result = JsonConvert.DeserializeObject<object>(json);

언급URL : https://stackoverflow.com/questions/13489139/how-to-write-json-string-value-in-code

반응형