Read a JSON from a URL

2

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

I have no idea how to do this, do you have any examples?

Note:

It's in Windows Phone 8 C #!

The response the url gives is as follows:

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

  

Url: link

    
asked by anonymous 23.04.2014 / 22:06

1 answer

2

Solution:

Download Package Json.NET , will be great utility for problem solving

Struct:

Createastructlikethis:

publicstructLayoutJson{publicLayoutJson(StringIndex,StringValue){_index=Index;_value=Value;}privatestring_index;publicstringIndex{get{return_index;}set{_index=value;}}privatestring_value;publicstringValue{get{returnthis._value;}set{this._value=value;}}}

ReadingroutineandstandardizationofthisJson

//ListadeValoresIList<LayoutJson>ResultJson;//MetodoqueéresponsávelporconectarnaurlebaixaroconteudopublicvoidGetJsonUrl(){WebClientweb=newWebClient();web.DownloadStringCompleted+=web_DownloadStringCompleted;web.DownloadStringAsync(newUri("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;
    }
}

Notes:

Notice that in the routine a Split was used in the return of the site content, because it came like this:

Thatis,thestringwassplittoonlygetJson.

AnotherimportantfactoristhatthisJsondoesnotfollowastandard,soitcreatesastructtostoreeachpositionofthesame,ifithadadefaultitwouldmakeaJsonConvert.DeserializeObject<T>,whereTwouldbeclassorstruct

Result

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

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

or, as you prefer

    
24.04.2014 / 01:37