Little Fox
Little Fox

Reputation: 1252

How to get values from JSON?

I want to output messages from website: vk.com, if I will type in browser: https://api.vk.com/method/"+method+"?"+param+"&v=5.31&access_token="+myAuth.Token1+"" with correct filled variables, I will get a page with:

"response":{"count":12455,"items":[{"id":19506,"date":1431024353,"out":0,"user_id":65896237,"read_state":1,"title":" ... ","body":"Message"}...

How can I get those values (id,date,body) from JSON? If I run my an attempt of code, I get window with save or open that JSON file...

        private void button3_Click(object sender, EventArgs e)
        {
            string method = "messages.get";
            string param = "out";
            string url = "https://api.vk.com/method/"+method+"?"+param+"&v=5.31&access_token="+myAuth.Token1+"";
            webBrowser1.ScriptErrorsSuppressed = true;
            webBrowser1.Navigate(url);   
        }

Upvotes: 1

Views: 941

Answers (4)

EGN
EGN

Reputation: 2572

Take your entire JSON response and post it here, and generate your classes. If you do it successfully you will have something like this

public class Item
{
    public int id { get; set; }
    public int date { get; set; }
    public int @out { get; set; }
    public int user_id { get; set; }
    public int read_state { get; set; }
    public string title { get; set; }
    public string body { get; set; }
}

public class Response
{
    public int count { get; set; }
    public List<Item> items { get; set; }
}

public class RootObject
{
    public Response response { get; set; }
}

Then in your code you can

WebClient client = new WebClient();
string json = client.DownloadString(url);
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
RootObject response = (RootObject) json_serializer.Deserialize(json, typeof(RootObject));

Now response has your information, and you can simply loop through your items

Upvotes: 4

jeffkempf
jeffkempf

Reputation: 358

Have you tried using the JsonConvert class? I created a server using Web API and used JsonConvert to automatically deserialize the Json values for me. Here's an example of what I mean:

using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("base url");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("specific url extention"); //this will asynchronously call server
            if (response.IsSuccessStatusCode) //test if http connection made
            {
                string s = await response.Content.ReadAsStringAsync();
                List<string> fooList = JsonConvert.DeserializeObject<List<string>>(s);
                for (int i = 0; i < 3; i++)
                {
                    string id = fooList[0];
                    string date = fooList[1];
                    string body = fooList[2];
                }
        }

I hope this helps.

Upvotes: 1

Blorgbeard
Blorgbeard

Reputation: 103467

Instead of using a WebBrowser control, use WebClient.DownloadString:

WebClient client = new WebClient();
string json = client.DownloadString(url);

This gets you the JSON as a string, without displaying any UI.

You still have to parse the values out of the JSON - I'm not sure if you know how to do that or not, since you got stuck on the WebBrowser thing. Anyway, I suggest trying the Json.net library.

Upvotes: 1

Andre Mesquita
Andre Mesquita

Reputation: 918

I created a dialog with jQuery UI which call with ajax, a mvc controller to return all products.

Javascript:

$dialog = $("#dlgCadastroProduto").dialog({
    modal: true,
    autoOpen: false,
    height: 500,
    width: 700,
    buttons: {
        Ok: function () {
            $(this).dialog("close");                
            $("#lstProducts").empty();
            $("#lstSelectedProducts").empty();
            $.ajax({
                type: "GET",
                url: '/Product/jsonLoad',
                async: true,
                dataType: 'json',
                success:
                    function (data) {
                      //alert('success');
                      $.each(data, function (index, value) {
                        $("#lstProducts").append('<option value='+value.ID+'>'+value.Description+'</option>')                    
                      });
                    },
                error: function (data) {
                     //alert(data);
                }
            });
        }
    }
});

C#:

public JsonResult jsonLoad()
{
   var list = _productBLL.FindAll();
   var xpto = list.Select(x => new { Id = x.ID, Description = x.Description });
   return Json(xpto, JsonRequestBehavior.AllowGet);
}

I hope I have helped!

Upvotes: 0

Related Questions