JSON.NET을 사용하여 서비스에서받은 JSON 문자열을 비즈니스 개체로 deseralize합니다.
주어진 REST URL의 모든 JSON 문자열을 다음과 같이 객체로 구문 분석하는 멋진 서비스 패턴이 있습니다.
private async Task<T> LoadJSONToObject<T>(string url)
{
//get data
var json = await GetResultStringAsync(url);
//deserialize it
var results = JsonConvert.DeserializeObject<T>(json);
return results;
}
내가 가진 도전은 "컨테이너"클래스를 만들지 않고 컬렉션과 함께 위의 패턴을 사용하는 방법입니다.
예를 들어 다음 JSON을 다시 얻는 경우 :
{
"Properties": [
{
"id": 1,
"name": "Property Name A",
"address": "Address A, City, Country",
},
{
"id": 2,
"name": "Property Name B",
"address": "Address B, City, Country",
}
]
}
내 사업체는 다음과 같습니다.
public class Property
{
[JsonProperty("id")]
public string ID { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("address")]
public string Address{ get; set; }
}
다음을 호출하여 위의 메서드를 간단히 호출하고 싶습니다.
LoadJSONToObject<List<Property>>("http://www.myapi.com/properties");
JSON.NET이 대신 컨테이너 객체를 기대하기 때문에 위의 내용은 실패합니다. 다음과 같은 것 :
public class PropertyList
{
[JsonProperty("Properties")]
public List<Property> Properties { get; set; }
}
그런 컨테이너를 만드는 것은 과잉이라고 생각하고 위의 작업을 수행하는 우아한 솔루션이 있는지 확인하고 싶습니다.
다음 LoadJSONToObject
과 같이 다시 작성하면이를 수행 할 수 있습니다 .
private async Task<T> LoadJSONToObject<T>(string url, string rootProperty)
{
//get data
var json = await GetResultStringAsync(url);
if (string.IsNullOrWhiteSpace(rootProperty))
return JsonConvert.DeserializeObject<T>(json);
var jObject = JObject.Parse(json);
var parsedJson = jObject[rootProperty].ToString();
//deserialize it
return JsonConvert.DeserializeObject<T>(parsedJson);
}
메서드 호출은
LoadJSONToObject<List<Property>>("http://www.myapi.com/properties", "Properties");
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다