user2970725
user2970725

Reputation:

How to parse Json content from a url with c#?

I made a little example:

public class Test
{
    [JsonProperty(PropertyName = "test1")]
    public String Test1 { get; set; }

    [JsonProperty(PropertyName = "test2")]
    public String Test2 { get; set; }
}

private string url = "http://sample.php";
private List<Test> TestList = new List<Test>();

private async Task<Test> getTestObjects()
{
    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync(url);
}

How do I get the Test objects from the url link into the TestList? Is it the same as reading XML?

Upvotes: 1

Views: 29987

Answers (2)

Jason Hitchings
Jason Hitchings

Reputation: 677

A fast and easy way to semi-automate these steps is to:

  1. take the JSON you want to parse and paste it here: http://json2csharp.com/ then copy and paste the resulting into a new class (ex: MyClass) in visual studio.
  2. Rename "RootObject" in the output from json2csharp to "MyClass" or whatever you called it.
  3. In visual studio go to Website -> Manage Packages and use NuGet to add Json.Net from Newtonsoft.

Now use code like:

WebClient client = new WebClient();

string myJSON = client.DownloadString("https://URL_FOR_JSON.com/JSON_STUFF");

var myClass = Newtonsoft.Json.JsonConvert.DeserializeObject(myJSON);

Upvotes: 3

Mohamad Shiralizadeh
Mohamad Shiralizadeh

Reputation: 8765

best way to parse json is Json.NET

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;
// Bad Boys

I try this code and works:

void Main()
{
    var test = Newtonsoft.Json.JsonConvert.DeserializeObject<Test>(getTestObjects().Result).Dump();

    // test.MyName; 'Bad Boys'
    // test.ReleaseDate; '1995-4-7T00:00:00'
}

public class Test
 {   
     [JsonProperty("Name")]
     public String MyName { get; set; }
     public String ReleaseDate { get; set; }
 }

 private string url = "http://bitg.ir/files/json.txt";
 private List<Test> TestList = new List<Test>();

 private async Task<String> getTestObjects()
 {
     var httpClient = new HttpClient();
     var response = await httpClient.GetAsync(url);
     var result = await response.Content.ReadAsStringAsync();

     return result;
 }

Upvotes: 2

Related Questions