자식 데이터 객체 배열로 JsonArray를 어떻게 만들 수 있습니까? 웹 서비스와 C #을 사용하고 있습니다.
JsonArray의 결과가 다음과 같기를 바랍니다.
[{
"name": "Deadpool",
"url": {
"small": "http://api.android.info/images/small/deadpool.jpg",
"medium": "http://api.android.info/images/medium/deadpool.jpg",
"large": "http://api.android.info/images/large/deadpool.jpg"
},
"time": "February 12, 2016"
},
{
"name": "The Jungle Book",
"url": {
"small": "http://api.android.info/images/small/book.jpg",
"medium": "http://api.android.info/images/medium/book.jpg",
"large": "http://api.android.info/images/large/book.jpg"
},
"time": "April 15, 2016"
},
{
"name": "X-Men: Apocalypse",
"url": {
"small": "http://api.android.info/images/small/xmen.jpg",
"medium": "http://api.android.info/images/medium/xmen.jpg",
"large": "http://api.android.info/images/large/xmen.jpg"
},
"time": "May 27, 2016"
}]
먼저 주어진 데이터를 출력 할 수있는 모델을 만듭니다. 당신은 MovieModel
, 영화가 여러 이미지 크기와 URL을 저장할 수 있습니다. 우리는 이것을 위해 사전을 사용합니다.
업데이트 됨
MovieModel.cs
public class MovieModel
{
public string Name { get; set; }
public Dictionary<string,string> Url { get; set; }
public string Time { get; set; }
}
이제 Newtonsoft.Json
Nuget 패키지에서 설치해야 합니다. 그런 다음 가져옵니다.
using Newtonsoft.Json;
모델을 초기화하고 SerializeObject()
메서드를 사용하여 Json으로 변환합니다 .
var movieList = new List<MovieModel>
{
new MovieModel
{
MovieName = "Deadpool",
Time = DateTime.UtcNow.ToString("t"),
Url = new Dictionary<string, string>
{
{ "small", "http://api.android.info/images/small/deadpool.jpg" },
{ "medium", "http://api.android.info/images/medium/deadpool.jpg" }
}
}
// .. add more movies .. //
};
// convert to camelcase and set indentation
var output = JsonConvert.SerializeObject(
movieList,
Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
);
// testing output on console
Console.WriteLine(output);
실제 응용 프로그램에서는이 예제에 사용 된대로 직접 초기화하지 않고 데이터베이스에서 데이터를 가져와 Movie 인스턴스를 만듭니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다