Read a JSON from a URL

Asked

Viewed 3,975 times

2

I need to read a JSON file, which is generated by PHP, through the json_encode;

I have no idea how to do this, you have some example?

Observing:

Is in Windows Phone 8 C#!

The answer the url gives is the following:

{"0":"1","id":"1","1":"0","churros":"0","2":"0","crepes":"0","3":"1","aberto":"1","4":"0","pulapula":"0"}

Url: http://webradioelectro.comxa.com/informacoes.php

  • Do you want to do this by javascript or php? If by js you can use the function of the jQuery called $.getJSON(); Doc: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CC8QFjAA&url=http%3A%2F%2Fapi.jquery.com%2Fjquery.getjson%2F&ei=fR5YU9ycNYet2QXk0oEY&usg=AFQjCNEB9qOPBeSVZLiVcekqkCXbTffRMA&sig2=0VSgsOL9A-iSrVW8MBphgA&bvm=bv.65177938,d.b2I It returns to you a js object.

  • @Randsonjarthis I want to do in windows phone 8. Ta in tag (:

  • 1

    This page does not return a application/json .

  • @Beet on android I managed to make...

  • @Bacco on Windows Phone 8 C#

1 answer

2


Solution:

Download the Package Json.NET, will be of great use for solving the problem

inserir a descrição da imagem aqui

Struct:

Create a struct like this:

public struct LayoutJson
{        
    public LayoutJson(String Index, String Value)           
    {
        _index = Index;
        _value = Value;
    }
    private string _index;    
    public string Index
    {
        get { return _index; }
        set { _index = value; }
    }
    private string _value;    
    public string Value
    {
        get { return this._value; }
        set { this._value = value; }
    }
}

Json Reading and Standardization Routine

//Lista de Valores
IList<LayoutJson> ResultJson;

//Metodo que é responsável por conectar na url e baixar o conteudo
public void GetJsonUrl()
{
    WebClient web = new WebClient();
    web.DownloadStringCompleted += web_DownloadStringCompleted;
    web.DownloadStringAsync(new Uri("http://webradioelectro.comxa.com/informacoes.php", UriKind.RelativeOrAbsolute));            
}
void web_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
    {
        string[] results = e.Result.Split(new string[1] { "<!--" }, StringSplitOptions.RemoveEmptyEntries);
        if (results.Count() > 0)
        {
            IEnumerable objetoJson = (IEnumerable)JsonConvert.DeserializeObject(results[0]);
            ResultJson = new List<LayoutJson>();
            foreach (var item in objetoJson)
            {
                string[] values = null;
                if (DescribeKeyValue(item, ref values))
                {
                    ResultJson.Add(new LayoutJson(values[0], values[1]));
                }                        
            }                    
        }
    }
}
//Descobre o Valor de cada item
bool DescribeKeyValue(object item, ref string[] values)
{
    try
    {
        if (item != null)
        {
            values = item.ToString().Replace("{", "").Replace("}", "").Split(':');
            return true;
        }
        return false;
    }
    catch
    {
        return false;
    }
}

Remarks:

Note that in the routine was used a Split on the return of the contents of the site, because it came this way:

inserir a descrição da imagem aqui

That is, it was divided to string to catch only the Json.

Another important factor to say that this Json does not follow the pattern, so created a struct to guard each position of the same, if it had a pattern would give to make a JsonConvert.DeserializeObject<T>, where T would be a class or struct

Upshot

inserir a descrição da imagem aqui

10 items were obtained with Index and Value, now just work on the programming like this:

foreach (LayoutJson item in ResultJson)
{
       //item.Index
       //item.Value
}

or, as you prefer

  • It is giving error, saying that the list is empty. When I try to call it in main, the list comes back empty or null

  • It depends if you followed step by step, you must be missing something, post your code on pastebin.com that I look at.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.