如何在Xamarin.Forms中使用RESTful服务获取JSON数据
由于我是Xamarin的新手,如果有人能用最简单的例子向我解释如何使用Xamarin表单使用RESTful服务(返回JSON数据),我将不胜感激。您可以使用JSON.net和HTTP请求,下面是一个如何使用电影数据库的快速示例,这是一个免费的电影数据库GET和POST示例,希望这有助于:如何在Xamarin.Forms中使用RESTful服务获取JSON数据,xamarin,xamarin.forms,Xamarin,Xamarin.forms,由于我是Xamarin的新手,如果有人能用最简单的例子向我解释如何使用Xamarin表单使用RESTful服务(返回JSON数据),我将不胜感激。您可以使用JSON.net和HTTP请求,下面是一个如何使用电影数据库的快速示例,这是一个免费的电影数据库GET和POST示例,希望这有助于: const string _baseUrl = "http://api.themoviedb.org/3/"; const string _pageString = "&page="; //GET E
const string _baseUrl = "http://api.themoviedb.org/3/";
const string _pageString = "&page=";
//GET Example
public static async Task<ObservableCollection<Movie>> GetTopRatedMoviesAsync(int page = 1)
{
HttpClient client = new HttpClient();
//_apiKey = themoviedb api key, page = page size 1 = first 20 movies;
string topRatedUrl = _baseUrl + "movie/top_rated?" + _apiKey + _pageString + page;
HttpResponseMessage result = await client.GetAsync (topRatedUrl, CancellationToken.None);
if (result.IsSuccessStatusCode) {
try{
string content = await result.Content.ReadAsStringAsync ();
ObservableCollection<Movie> MovieList = GetJsonData(content);
//return a ObservableCollection to fill a list of top rated movies
return MovieList;
}catch(Exception ex){
//Model Error
Console.WriteLine (ex);
return null;
}
}
//Server Error or no internet connection.
return null;
}
static ObservableCollection<Movie> GetJsonData(string content){
JObject jresponse = JObject.Parse (content);
var jarray = jresponse ["results"];
ObservableCollection<Movie> movieList = new ObservableCollection<Movie> ();
foreach (var jObj in jarray) {
Movie newMovie = new Movie();
newMovie.Title = (string)jObj["title"];
newMovie.PosterPath = _baseImgUrl + (string)jObj["poster_path"];
newMovie.HighResPosterPath = _baseImgUrl + (string)jObj["poster_path"];
newMovie.Id = (int)jObj["id"];
newMovie.Overview = (string)jObj["overview"];
newMovie.VoteCount = (double)jObj["vote_count"];
newMovie.ReleaseDate = (DateTime)jObj["release_date"];
newMovie.VoteAverage = (float)jObj["vote_average"];
movieList.Add(newMovie);
}
return movieList;
}
//POST Example:
public static async Task<bool> PostFavoriteMovieAsync(Movie movie)
{
try
{
HttpClient client = new HttpClient();
//_sessionId = string with the movie database session.
string tokenUrl = _baseUrl + "account/id/favorite?" + _apiKey + _sessionId;
string postBody = JsonConvert.SerializeObject(new Favorite{
favorite = !movie.Favorite,
media_id = movie.Id,
});
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsync (tokenUrl,
new StringContent (postBody, Encoding.UTF8, "application/json"));
if(response.IsSuccessStatusCode)
return true;
else
return false;
}
catch(Exception ex){
Console.WriteLine (ex.Message);
return false;
}
}
const字符串\u baseUrl=”http://api.themoviedb.org/3/";
常量字符串_pageString=“&page=”;
//以身作则
公共静态异步任务GetTopRatedMoviesAsync(int page=1)
{
HttpClient=新的HttpClient();
//_apiKey=MovieDB api key,页面=页面大小1=前20部电影;
字符串topRatedUrl=\u baseUrl+“电影/顶级?”+\u apiKey+\u页面字符串+页面;
HttpResponseMessage结果=wait client.GetAsync(topRatedUrl,CancellationToken.None);
if(结果。IsSuccessStatusCode){
试一试{
string content=wait result.content.ReadAsStringAsync();
ObservableCollection MovieList=GetJsonData(内容);
//返回ObservableCollection以填充顶级电影列表
回归电影人;
}捕获(例外情况除外){
//模型误差
Console.WriteLine(ex);
返回null;
}
}
//服务器错误或没有internet连接。
返回null;
}
静态ObservableCollection GetJsonData(字符串内容){
JObject jresponse=JObject.Parse(内容);
var jarray=jresponse[“结果”];
ObservableCollection movieList=新的ObservableCollection();
foreach(jarray中的var jObj){
Movie newMovie=新电影();
newMovie.Title=(字符串)jObj[“Title”];
newMovie.PosterPath=_baseImgUrl+(字符串)jObj[“poster_path”];
newMovie.HighResPosterPath=_baseImgUrl+(字符串)jObj[“poster_path”];
Id=(int)jObj[“Id”];
newMovie.Overview=(字符串)jObj[“Overview”];
newMovie.VoteCount=(双)jObj[“投票计数”];
newMovie.ReleaseDate=(DateTime)jObj[“release_date”];
newMovie.VoteAverage=(float)jObj[“投票平均数”];
movieList.Add(newMovie);
}
回归电影人;
}
//帖子示例:
公共静态异步任务PostFavoriteMovieAsync(电影)
{
尝试
{
HttpClient=新的HttpClient();
//_sessionId=包含电影数据库会话的字符串。
字符串tokenUrl=\u baseUrl+“account/id/favorite?”+\u apiKey+\u sessionId;
string postBody=JsonConvert.SerializeObject(新收藏夹{
favorite=!movie.favorite,
media\u id=movie.id,
});
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
HttpResponseMessage response=await client.PostAsync(令牌URL,
新的StringContent(postBody,Encoding.UTF8,“application/json”);
if(响应。IsSuccessStatusCode)
返回true;
其他的
返回false;
}
捕获(例外情况除外){
Console.WriteLine(例如消息);
返回false;
}
}
试试这个