1

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?

1
  • Download the json text first, then decode it. This splits your single question into two, how to download, and how to parse. Commented Dec 6, 2014 at 20:45

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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;
 }

2 Comments

Yes that works indeed! But what is the difference between [JsonProperty(PropertyName = "test1")] public String Test1 { get; set; } and public String Name { get; set; }? I mean the JsonProperty above the Property.
@user2970725 I correct the answer. JsonProperty make your property map to a json property if you want names to be different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.