user217648
user217648

Reputation: 3466

Getting json string programmatically C#

I am trying to get json string from a url by using following line of code. When I enter the url in Google Chrome I get whole string and data. but when I use my code it returns only this line of string
{"expand":"projects","projects":[]}
it is exact what I get when I enter the url in IE 10. How can I get same data that I get when I enter the url in Chrome? here is my code to get the json data.
var jsonStr = new WebClient().DownloadString("https_my_url");

Upvotes: 1

Views: 444

Answers (2)

Mesh
Mesh

Reputation: 6422

You will need to authenticate the request via WebClient.

See this answer for how to do that if the site uses Forms Authentication.

WebClient accessing page with credentials

Upvotes: 1

Moo-Juice
Moo-Juice

Reputation: 38825

You need to use a JSON parser to turn it in to something useful. ServiceStack.Text (available via NuGet or download) has an excellent one that can turn json strings in to first-class POCOs.

using ServiceStack.Text;

public sealed class SomeObject
{
    public string expand { get; set; }
    public List<string> projects {get; set; }
}

And convert thusly:

SomeObject object = jsonString.FromJson<SomeObject>();

Note, I would make my POCOs a little more c# friendly and alias away the lower-case:

using ServiceStack.Text;
using ServiceStack.DataAnnotations;

public sealed class SomeObject
{
    [Alias("expand")]
    public string Expand { get; set; }

    [Alias("projects")]
    public List<string> Projects {get; set; }
}

Upvotes: 0

Related Questions