we have an URL which contains the JSON data, now I am trying to use JSON.Net to read it.
step1: set up
- create a website in visual studio and right click the Solution Explorer panel on the left, select Manage NuGet Package...
- notice to switch Package source to All or nuget.org and then Browse "Newtonsoft.Json" and install
Ref: https://docs.microsoft.com/en-us/nuget/tools/package-manager-ui
step2: create model
add a .cs file as a container, name it corresponding to the JSON object in that URL. There are many ways to auto generate the attributes from that URL, one way is go to this website: http://json2csharp.com/#;
Another way is copy the JSON file then go the the model.cs file, click Edit button on the top of VisualStudio click Specialpaste - paste JSON as Classes, my model is like this:
FoodNearbyModel.cs
public class FoodNearbyModel
{
public string API_Status { get; set; }
public string AdminRemarks { get; set; }
public string Category { get; set; }
public string ContactEmail { get; set; }
public string ContactInfo { get; set; }
public string ContactNumber { get; set; }
public string ContactStatus { get; set; }
public float Distance { get; set; }
public string EatBookArticle { get; set; }
public string EntryAddress { get; set; }
public string EntryDescription { get; set; }
public int EntryID { get; set; }
public string EntryName { get; set; }
public string FacebookPage { get; set; }
public string Instagram { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
public string MasterCategory { get; set; }
public string OpeningHours { get; set; }
public string PostalCode { get; set; }
public string SubFilter { get; set; }
public string TSLArticle { get; set; }
public string TSLReviews { get; set; }
public string Website { get; set; }
public string Zone { get; set; }
}
step3: create JSonParser
add another .cs file name as JSonParser
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using Newtonsoft.Json;
public class JSonParser
{
const string url = "https://appsbytsl.com/API/V1/Nearby/Food/H4D3S/1.319190/103.857834/3";
static List<FoodNearbyModel> foodNearby;
//public JSonParser()
//{
// string json = new WebClient().DownloadString(url);
// foodNearby = JsonConvert.DeserializeObject<List<FoodNearbyModel>>(json);
//}
public static void initialise()
{
string json = new WebClient().DownloadString(url);
foodNearby = JsonConvert.DeserializeObject<List<FoodNearbyModel>>(json);
}
public static List<FoodNearbyModel>GetAll()
{
initialise();
return foodNearby;
}
public static List<string> GetByCategory()
{
initialise();
return foodNearby.Select(x => x.Category).Distinct().ToList();
}
}
step4: call JSonParse in webForm
using System;
public partial class DefaultPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = JSonParser.GetAll();
GridView1.DataBind();
}
}