Developer forum

Forum » Templates » How do i fetch and display json data, using razor?

How do i fetch and display json data, using razor?

Hans Ravnsfjall
Hans Ravnsfjall
Reply

I know how to do it for fetching and displaying XML, and tought it would be easy to convert this code to fetch json instead, but I can´t get it to work.

 

Here is what I have for XML, and this works perfectly.

 

 

 

Pardon the clumsy code, but this is just a test

 

@using System.Xml.Linq
@using System.Xml
@using System.Linq
 
@{
XmlDocument xml = new XmlDocument();
xml.Load("http://www.www.com/myfeed");
XmlNodeList nodes = xml.SelectNodes("//Observation");
 
}
 
<!doctype html>
<html lang="fo">
<head>
</head>
<body>
@foreach(XmlNode node in nodes)
{
 
var stationid = node.SelectSingleNode("StationId").InnerText;
var stationname = node.SelectSingleNode("StationName").InnerText;
var date = node.SelectSingleNode("Date").InnerText;
var time = node.SelectSingleNode("Time").InnerText;
var lat = node.SelectSingleNode("Lat").InnerText;
var longitude = node.SelectSingleNode("Long").InnerText;
var avgwind = node.SelectSingleNode("AvgWind").InnerText;
var maxwind = node.SelectSingleNode("MaxWind").InnerText;
var winddir = node.SelectSingleNode("WindDir").InnerText;
var temperature = node.SelectSingleNode("Temperature").InnerText;
var roadtemperature = node.SelectSingleNode("RoadTemperature").InnerText;
var pressure = node.SelectSingleNode("Pressure").InnerText;
var humidity = node.SelectSingleNode("Humidity").InnerText;
var rainintensity = node.SelectSingleNode("RainIntensity").InnerText;
var cloudstatus = node.SelectSingleNode("CloudStatus").InnerText;
var roadstatus = node.SelectSingleNode("RoadStatus").InnerText;
var windwarning = node.SelectSingleNode("WindWarning").InnerText;
var f_link = node.SelectSingleNode("F_Link").InnerText;
<text>
stationid - @stationid <br /><br />
stationname - @stationname <br /><br />
date - @date <br /><br />
time - @time <br /><br />
lat - @lat <br /><br />
longitude - @longitude <br /><br />
avgwind - @avgwind <br /><br />
maxwind - @maxwind <br /><br />
winddir - @winddir <br /><br />
temperature - @temperature <br /><br />
roadtemperature @roadtemperature <br /><br />
pressure - @pressure <br /><br />
humidity - @humidity <br /><br />
rainintensity - @rainintensity <br /><br />
cloudstatus - @cloudstatus <br /><br />
roadstatus - @roadstatus <br /><br />
windwarning - @windwarning <br /><br />
f_link - @f_link <br /><br />
<hr />
<br /><br />
</text>
}

 

Anybody have a hint on how I can change this to fetch JSON instead?

 

/Hans


Replies

 
Hans Ravnsfjall
Hans Ravnsfjall
Reply
 
Claus Kølbæk
Claus Kølbæk
Reply

Hi Hans

 

There are many ways to do this, but one way would be to make a class containing all your fields.

and then do something like this:

@using Newtonsoft.Json
@using System.Web.Script.Serialization;

@functions{

    public class MyClass{

      //get; set; variables for all your fields

   }

}

using (webClient) {

       string url = "www.www.com";
        string json_data = client.DownloadString(url);
        var result = JsonConvert.DeserializeObject<MyClass>(json_data);        
    }

 

Short example :) But for more, try googling a bit for  JsonConvert.DeserializeObject

 
Hans Ravnsfjall
Hans Ravnsfjall
Reply

Hi Claus

 

thanks for the Help :) I presume I then can loop through the Var result to show the different instances?

 

/Hans

 
Claus Kølbæk
Claus Kølbæk
Reply

The result is whatever you have made your class to be. So if you have multiple items it would make sense to have a variable in your class with fx List<MyNewClass> and then define your item fields in a new Class.

It depends a bit on the structure of Json, but fx you could have something like this: 

RootClass{

List<Node> Nodes

}

Node{

string stationId {get;set;}

}

and then you would be able to iterate over the nodes in your root class - hope that makes sense :) - again it depends abit on the json structure.

 
Hans Ravnsfjall
Hans Ravnsfjall
Reply

Ok, thank you very mutch

so far I have this, but this gives an error. Any suggestions why?

 

@using System.Web.Script.Serialization
@using System
@using System.Net
@using System.Collections.Generic
@using System.Dynamic
@using System.Linq
@using Newtonsoft.Json.Converters
@using Newtonsoft.Json
@using System.IO
@using Newtonsoft.Json.Linq
 
@functions{
public class Station
{
 
public List<WeatnerStation> data {get; set;}
}
 
public class WeatnerStation
{
 
public string StationName {get; set;}
public string Id {get; set;}
}
}
 
@{
string url = "http://www.www.com/feed";
var client = new System.Net.WebClient();
string downloadString = client.DownloadString(@url);
 
Station WeatnerStation = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Station>(url);
 
foreach(var item in WeatnerStation.data)
{
Console.WriteLine("StationName: {0}, Id: {1}", item.StationName, item.Id);
}
 
}
 
Imar Spaanjaars Dynamicweb Employee
Imar Spaanjaars
Reply

You're trying to deserialize the URL, not the returned data. So this:

Station WeatnerStation = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Station>(url);

should be this:

Station WeatnerStation = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Station>(downloadString);

When you post code here, can you clean it up a bit and maybe format it with the "Formatted" option? Makes it easier for people to read and use your code without lots of cleanup of linebreaks and such first.

Cheers,

Imar

 
Hans Ravnsfjall
Hans Ravnsfjall
Reply

Thank you very mutch Imar

Sorry for the messy posts. Not sure how to clean it up when copying from Visual Studio Code

But in the end I solved it like this

 

@{
        
string url = "http://www.www.com/";
var client = new System.Net.WebClient();
string downloadString = client.DownloadString(@url);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(downloadString);

foreach (var obj in jsonObj.Data)
{
    <p> <strong> @obj.StationName </strong> </p>
}

    }

 

 

 
Imar Spaanjaars Dynamicweb Employee
Imar Spaanjaars
Reply

Yeah, that looks great. Glad you got it working.

>> Not sure how to clean it up when copying from Visual Studio Code

I usually paste it in Notepad or so first to get rid of the formatting.

Cheers,

Imar

 
Hans Ravnsfjall
Hans Ravnsfjall
Reply

ok, thank you Imar 👍🏻

 

You must be logged in to post in the forum