C#을 사용하여 JSON 텍스트를 개체로 변환하는 방법
다음 JSON 응답을 C# 객체로 변환하려면 어떻게 해야 합니까?
{
"err_code": "0",
"org": "CGK",
"des": "SIN",
"flight_date": "20120719",
"schedule": [
["W2-888","20120719","20120719","1200","1600","03h00m","737-200","0",[["K","9"],["F","9"],["L","9"],["M","9"],["N","9"],["P","9"],["C","9"],["O","9"]]],
["W2-999","20120719","20120719","1800","2000","01h00m","MD-83","0",[["K","9"],["L","9"],["M","9"],["N","9"]]]
]
}
json 문자열에서 클래스를 만들려면 문자열을 복사합니다.
Visual Studio 상단의 메뉴에서 [Edit]> [ Paste Special ]> [ Paste Json as classes ]을 클릭합니다.
Newtonsoft를 설치합니다.Nuget 경유 Json
다음 코드를 프로젝트에 붙여넣습니다. "jsonString"은 역직렬화할 변수입니다.
Rootobject r = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(jsonString);
알기 쉽게 루트 오브젝트의 이름을 변경하는 것을 잊지 말아 주세요.
ILoveTheSmellOfNapalmInTheMorning
-그건 장난이었어.
먼저 json 데이터를 나타내는 클래스를 만듭니다.
public class MyFlightDto
{
public string err_code { get; set; }
public string org { get; set; }
public string flight_date { get; set; }
// Fill the missing properties for your data
}
Newtonsoft JSON serializer를 사용하여 json 문자열을 대응하는 클래스 객체로 역직렬화합니다.
var jsonInput = "{ org:'myOrg',des:'hello'}";
MyFlightDto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<MyFlightDto>(jsonInput);
또는 사용JavaScriptSerializer
클래스로 변환합니다(뉴턴소프트 json 시리얼라이저가 더 나은 성능을 발휘하는 것 같기 때문에 권장되지 않습니다).
string jsonInput="have your valid json input here"; //
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Customer objCustomer = jsonSerializer.Deserialize<Customer >(jsonInput)
변환이 필요한 경우Customer
classe의 인스턴스당신의 클래스는 다음과 비슷해야 합니다.JSON
구조(속성)
를 사용하는 것이 좋습니다.이 라이브러리는 오픈소스 라이브러리로 c# 개체를 json 개체로 시리얼화하고 json 개체를 .net 개체로 시리얼 해제하는 것입니다.
시리얼화의 예:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
다른 JSON 시리얼라이제이션 기술과의 퍼포먼스 비교
Json을 복사하여 http://json2csharp.com/ 텍스트 상자에 붙여넣고 Generate 버튼을 클릭합니다.
다음과 같이 cs 파일을 사용하여 cs 클래스가 생성됩니다.
varcs generatedResponce = JsonConvert.Diserialize Object(your Json);
여기서 Root Object는 생성된 cs 파일의 이름입니다.
json 문자열을 사용하여 지정한 클래스로 변환합니다.
public static T ConvertJsonToClass<T>(this string json)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Deserialize<T>(json);
}
class Program
{
static void Main(string[] args)
{
var res = Json; //Json that has to be converted
Response resp = new Response();
resp = JsonSerializer.Deserialize<Response>(res);
Console.WriteLine(res);
}
}
public class Response
{
public bool isValidUser { get; set; }
public string message { get; set; }
public int resultKey { get; set; }
}
언급URL : https://stackoverflow.com/questions/11260631/how-to-convert-json-text-into-objects-using-c-sharp
'programing' 카테고리의 다른 글
리액트 후크 useEffect는 영속적으로 실행/무한 루프 (0) | 2023.03.18 |
---|---|
Newtonsoft를 사용하여 C#(4.0)의 json 문자열을 해석하는 방법Json 패키지? (0) | 2023.03.18 |
각도 사용UTC 날짜가 있는 JS 날짜 필터 (0) | 2023.03.13 |
"프로젝트 검색.." 기능이 Eclipse IDE에 있습니까? (0) | 2023.03.13 |
PLSQL : 신규 및 :늙은 (0) | 2023.03.13 |