Dart: Parse JSON to object

As we saw in the first post: http://www.signer.pro/lets-meet-dart/ its real easy to work with Dart. We want to parse the JSON-Objects, that you can get here(http://api.signer.pro/client.php?action=getCds) to Dart-Objects. First of all we will write a normal console application and after that a web application where we display the data a bit nicer.

Dart Console Application

First of all we create a cd-class with all the information we need:

class Cd {
  num id;
  String album;
  String interpret;

 Cd(num id, String album, String interpret){
  this.id = id;
  this.album = album;
  this.interpret = interpret;
 }

 Cd.fromJson(Map json){
  id = json['id'];
  album= json['album'];
  interpret = json['interpret'];
 }
}

Some of the relevant data types in our example are num and String. There is also bool, but we don’t need that one in the example.

So after we wrote the Dart-Object, let’s work with the main-method:

void main() {
List<Cd> listOfCds = new List<Cd>();
var httpClient = new HttpClient();
var conn = httpClient.getUrl(new Uri('http://api.signer.pro/client.php?action=getCds'));
conn.onResponse = (HttpClientResponse resp) {
var input = resp.inputStream;
input.onData = () {
var data = input.read();
var text = new String.fromCharCodes(data);
List l = JSON.parse(text);
l.forEach((map){
Cd c = new Cd(int.parse(map['id']), map['album'], map['interpret']);
listOfCds.add(c);
});
listOfCds.forEach((cd) {
print("album = ${cd.album} interpret = ${cd.interpret}");
});
};
input.onClosed = () => httpClient.shutdown();
};
}

We created a httpClient with the URL to the API. Then we get the response and get the text with the following command:

var text = new String.fromCharCodes(data);

Then we parse the JSON-text into a List. Because we’ve got a JSON-Array with some JSON-Objects. And now something that I love the most of the Dart-Language:

l.forEach((map){
Cd c = new Cd(int.parse(map['id']), map['album'], map['interpret']);
listOfCds.add(c);
});

This way, we can simply loop through a list and do something with the objects. In this case we map the value with the key ‘id’ or ‘album’ and create a Cd-Object with it. After that we add it to a list of Cd’s we defined earlier.

pp1

So, as wee see this is working pretty well. And now we do almost the some for a small web application.

Dart Web Application

As in the console application we define a CD-Object. After that we use the following code in the main-method:

void main() {
List<Cd> listOfCds = new List<Cd>();
ParagraphElement p = new ParagraphElement();
p.text = "loading..";
query("#container").append(p);
var request = new HttpRequest.get('http://api.signer.pro/client.php?action=getCds', (req) {
var text = req.responseText;
List l = JSON.parse(text);
l.forEach((map){
Cd c = new Cd(int.parse(map['id']), map['album'], map['interpret']);
listOfCds.add(c);
});
UListElement ule = new UListElement();
listOfCds.forEach((cd) {
LIElement lie = new LIElement();
lie.text = "${cd.album} (${cd.interpret})";
ule.children.add(lie);
});
p.remove();
query("#container").append(ule);
});
}

We needed to modify the code a bit, so it matches the the  ‘dart:html’ library. But the rest of the code is very similar to the code in the first example above. The HTML looks like that:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ConnectAPI</title>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet"></link>
</head>
<body>
<h1>ConnectAPI</h1>
<div class="span12" id="container">
</div>
<script type="application/dart" src="ConnectAPI.dart"></script>
<script src="https://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
</body>
</html>

As you see, I’m using bootstrap again for the website. So the result in the browser looks like that:

pp2

Yannick Signer

 

Leave a Reply

Your email address will not be published. Required fields are marked *