jupper
jupper

Reputation: 103

Map Json with dart

I'm trying to make a simple server app with dart. It should take an id and print the associated name. For example if i enter the url "http://localhost:4040/?id=12" in my browser I want "Heroname: Narco" to printed at the page.

This is the content of the file heros:

{'id': 11, 'name': 'Mr. Nice'}
{'id': 12, 'name': 'Narco'}
{'id': 13, 'name': 'Bombasto'}
{'id': 14, 'name': 'Celeritas'}
{'id': 15, 'name': 'Magneta'}
{'id': 16, 'name': 'RubberMan'}
{'id': 17, 'name': 'Dynama'}
{'id': 18, 'name': 'Dr IQ'}
{'id': 19, 'name': 'Magma'}
{'id': 20, 'name': 'Tornado'}

hero.dart

class Hero {
  final int id;
  String name;
  Hero(this.id, this.name);

  factory Hero.fromJson(Map<String, dynamic> hero) =>
      Hero(_toInt(hero['id']), hero['name']);

  Map toJson() => {'id': id, 'name': name};

}

int _toInt(id) => id is int ? id : int.parse(id);

hero_dart_service.dart

import 'dart:io';
import 'dart:async';
import 'dart:convert';

import '../angular_tour_of_heroes/lib/src//hero.dart';

String _host = InternetAddress.loopbackIPv4.host;
String path = 'heros';
List<Hero> heros = new List();
var list;

void main() async{
  list = await getData();
  var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 4040);
  print('Listening on localhost:${server.port}');

  await for (var request in server) {
    handleRequest(request);
  }

}

Future<List<String>> getData() async{
  List<String> list = new List();
  Stream lines = new     File(path).openRead().transform(utf8.decoder).transform(const LineSplitter());
  try {
      await for (var line in lines) {
        list.add(line);
      }
  } catch(e) {
      print(e);
      throw new Exception(e);
  }
  return list;
}

void handleRequest(HttpRequest request) {
  try {
    if (request.method == 'GET') {
      handleGet(request);
    } else {
      request.response
        ..statusCode = HttpStatus.METHOD_NOT_ALLOWED
        ..write('Unsupported request: ${request.method}.')
        ..close();
    }
  } catch (e) {
    print('Unsupported request: $e');
  }
}

handleGet(HttpRequest request) {
  heros = list.map((json) => Hero.fromJson(json)).toList();
  final id = request.uri.queryParameters['id'];
  var targetHero = heros.where((hero) => hero.id == id);
  var name = targetHero;//.name;
  final response = request.response;
  response.statusCode = HttpStatus.OK;
  response
    ..write('Heroname: $name')
    ..close();
}

When I launch the app, there's no error, but when I enter an url like "http://localhost:4040/?id=12" in the browser, I get this error message "Unsupported request: type 'String' is not a subtype of type 'Map".

I don't no why this doesn't work. Can anybody give me a hint?

Upvotes: 0

Views: 6221

Answers (1)

jupper
jupper

Reputation: 103

Ok, I solved it by my self. After I changed

heros to

{"id": 11, "name": "Mr. Nice"}
{"id": 12, "name": "Narco"}
{"id": 13, "name": "Bombasto"}
{"id": 14, "name": "Celeritas"}
{"id": 15, "name": "Magneta"}
{"id": 16, "name": "RubberMan"}
{"id": 17, "name": "Dynama"}
{"id": 18, "name": "Dr IQ"}
{"id": 19, "name": "Magma"}
{"id": 20, "name": "Tornado"}

And handleGet() to

handleGet(HttpRequest request) {
  heros = list.map((json) => Hero.fromJson(stringToMap(json))).toList();
  final id = request.uri.queryParameters['id'];
  var targetHero = heros.firstWhere((hero) => hero.id.toString() == id);
  var name = targetHero.name;
  final response = request.response;
  response.statusCode = HttpStatus.OK;
  response
    ..write('Heroname: $name')
    ..close();
}

Map<String, dynamic> stringToMap(String s) {
  Map<String, dynamic> map = json.decode(s);
  return map;
}

It works now.

Upvotes: 1

Related Questions