응답을 역 직렬화하는 데 도움이 필요합니다. (전화 번호로 Data247에 전화를 걸고 있으며 api는 이동 전화 사업자를 반환합니다). API 호출이 작동하고 다음과 같은 유효한 응답을 받고 있습니다.
{
"response": {
"status": "OK",
"results": [
{
"phone": "11234567890",
"wless": "y",
"carrier_name": "Blue Licenses Holding, LLC",
"carrier_id": 6,
"sms_address": "[email protected]",
"mms_address": "[email protected]"
}
]
}
}
이것은 C # .NET winforms 앱에 있습니다. 이를 테스트하려면 Data247의 액세스 키가 있어야합니다. 모든 것이 API 호출을 통해 작동합니다. 내 문제는 다음 줄에 있습니다.
Data247 data247 = JsonConvert.DeserializeObject<Data247>(response.Content);
... 그래서 내 수업이 올바르게 구성되어 있다고 생각하지 않습니다. ... 또는 내가 올바르게 역 직렬화하지 않을 수도 있습니다. 내 코드는 다음과 같습니다.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using RestSharp;
using Newtonsoft.Json;
namespace myTest
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btnVerify_Click(object sender, EventArgs e)
{
try
{
string request = txtEndpoint.Text;
request += "?key=" + txtAccessKey.Text;
request += "&api=CU";
request += "&phone=" + txtPhone.Text;
var client = new RestClient(request);
var response = client.Execute(new RestRequest());
Data247 data247 = JsonConvert.DeserializeObject<Data247>(response.Content);
MessageBox.Show(response.Content);
Debug.Print(response.Content);
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
}
}
public class Data247
{
Response response { get; set; }
public class Response
{
public string status { get; set; }
Results results { get; set; }
public class Results
{
List<Phone> phones = new List<Phone>();
public Phone phone { get; set; }
public class Phone
{
public string phone { get; set; }
public string wless { get; set; }
public string carrier_name { get; set; }
public string carrier_id { get; set; }
public string sms_address { get; set; }
public string mms_address { get; set; }
}
}
}
}
}
}
@Hirasawa의 권장 트릭 외에도이 모든 작동 방식을 이해하는 것이 중요하다고 생각하므로 코드에서 몇 가지 결함을 지적하고 싶습니다.
Phone 클래스가 필요하지 않습니다.
데이터 구조를 보면 전화 번호는 결과 항목의 속성 일뿐입니다. 또한 Results
배열이므로 이러한 오류를 수정하기 위해 코드를 업데이트 해 보겠습니다.
public class Data247
{
Response response { get; set; }
public class Response
{
public string status { get; set; }
public Results[] results { get; set; }
public class Results
{
public string phone { get; set; }
public string wless { get; set; }
public string carrier_name { get; set; }
public string carrier_id { get; set; }
public string sms_address { get; set; }
public string mms_address { get; set; }
}
}
}
대상 속성은 공용이어야합니다.
응답을 올바르게 역 직렬화하려면 대상 클래스의 속성이 public 이어야합니다 . 이러한 오류를 수정하면
public class Data247
{
public Response response { get; set; }
public class Response
{
public string status { get; set; }
public Results[] results { get; set; }
public class Results
{
public string phone { get; set; }
public string wless { get; set; }
public string carrier_name { get; set; }
public string carrier_id { get; set; }
public string sms_address { get; set; }
public string mms_address { get; set; }
}
}
}
위의 변경으로 이제 코드가 작동합니다. 글쎄, 거의 ;-). 이제 Results
라는 속성의 동일한 수준에 중첩 된 클래스가있는 것으로 나타났습니다 Results
. 이것은 C #에서 유효하지 않으며 컴파일러는 "이미 선언 된 Results 멤버가 있습니다." 오류와 함께이를 알려줍니다 . .
수정이 용이하지만, 우리는 단지 외부 범위에 중첩 된 클래스를 이동하거나 우리가 이름을 바꿀 수 Response
와 Results
같은 것으로 수업을 ResponseDTO
하고 ResultDTO
,하지만 난 할 이전보다 쉽게 찾을 수 있습니다. 이제 코드는 다음과 같습니다.
public class Data247
{
public Response response { get; set; }
}
public class Response
{
public string status { get; set; }
public Results[] results { get; set; }
}
public class Results
{
public string phone { get; set; }
public string wless { get; set; }
public string carrier_name { get; set; }
public string carrier_id { get; set; }
public string sms_address { get; set; }
public string mms_address { get; set; }
}
보너스 : 관용적 인 C # 코드를 작성합니다.
관용적 코드를 작성하려면 권장 속성 이름을 사용해야합니다. 이것은 스타일과 코드의 문제이지만 코드가 제대로 작성되면 C # 개발자가 감사 할 것입니다.
다음은 내가 할 일에 대한 간략한 요약입니다.
UpperCamelCase
형식으로 바꿉니다 . 예 : mms_address
이어야합니다 MmsAddress
.다음은 최종 코드입니다.
public class Data247
{
[JsonProperty("Response")]
public Response Response { get; set; }
}
public class Response
{
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("results")]
public Results[] Results { get; set; }
}
public class Results
{
[JsonProperty("Phone")]
public string Phone { get; set; }
[JsonProperty("wless")]
public string Wless { get; set; }
[JsonProperty("carrier_name")]
public string CarrierName { get; set; }
[JsonProperty("carrier_id")]
public string CarrierId { get; set; }
[JsonProperty("sms_address")]
public string SmsAddress { get; set; }
[JsonProperty("mms_address")]
public string MmsAddress { get; set; }
}
도움이 되었기를 바랍니다!
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다