как вставить неожиданный символ (в символ 1) в flutter

#json #flutter

#json #flutter

Вопрос:

почему у нас есть радиосервер со следующим файлом json

 {
  "icestats":{
    "admin":"icemaster@localhost",
    "host":"online.localhost.be",
    "location":"Earth",
    "server_id":"Icecast 2.4.4",
    "server_start":"Sun, 30 Aug 2020 10:50:52  0200",
    "server_start_iso8601":"2020-08-30T10:50:52 0200",
    "source":[
      {
        "audio_info":"ice-samplerate=44100;ice-bitrate=320;ice-channels=2",
        "bitrate":320,
        "genre":"oldies",
        "ice-bitrate":320,
        "ice-channels":2,
        "ice-samplerate":44100,
        "listener_peak":0,
        "listeners":0,
        "listenurl":"http://127.0.0.1:8000/mp3_320",
        "server_description":"Very Oldies!",
        "server_name":"loclahost",
        "server_type":"audio/mpeg",
        "server_url":"https://127.0.0.1:8000",
        "stream_start":"Sun, 30 Aug 2020 13:45:16  0200",
        "stream_start_iso8601":"2020-08-30T13:45:16 0200",
        "title":"1951: Four Knights - I Love The Sunshine Of Your Smile",
        "dummy":null
      },
      {
        "audio_bitrate":320000,
        "audio_channels":2,
        "audio_info":"ice-samplerate=44100;ice-bitrate=320;ice-channels=2",
        "audio_samplerate":44100,
        "bitrate":320,
        "genre":"oldies",
        "ice-bitrate":320,
        "ice-channels":2,
        "ice-samplerate":44100,
        "listener_peak":0,
        "listeners":0,
        "listenurl":"http://127.0.0.1:8000/ogg_320",
        "server_description":"Very Oldies!",
        "server_name":"localhost",
        "server_type":"application/ogg",
        "server_url":"https://127.0.0.1:8000",
        "stream_start":"Sun, 30 Aug 2020 13:45:16  0200",
        "stream_start_iso8601":"2020-08-30T13:45:16 0200",
        "subtype":"Vorbis",
        "dummy":null
      }
    ]
  }
}
  

если я проанализирую это с помощью этой модели, я получу ошибку «неожиданный символ в 1»

 class Autogenerated {
  Icestats icestats;

  Autogenerated({this.icestats});

  Autogenerated.fromJson(Map<String, dynamic> json) {
    icestats = json['icestats'] != null
        ? new Icestats.fromJson(json['icestats'])
        : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.icestats != null) {
      data['icestats'] = this.icestats.toJson();
    }
    return data;
  }
}

class Icestats {
  String admin;
  String host;
  String location;
  String serverId;
  String serverStart;
  String serverStartIso8601;
  List<Source> source;

  Icestats(
      {this.admin,
        this.host,
        this.location,
        this.serverId,
        this.serverStart,
        this.serverStartIso8601,
        this.source});

  Icestats.fromJson(Map<String, dynamic> json) {
    admin = json['admin'];
    host = json['host'];
    location = json['location'];
    serverId = json['server_id'];
    serverStart = json['server_start'];
    serverStartIso8601 = json['server_start_iso8601'];
    if (json['source'] != null) {
      source = new List<Source>();
      json['source'].forEach((v) {
        source.add(new Source.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['admin'] = this.admin;
    data['host'] = this.host;
    data['location'] = this.location;
    data['server_id'] = this.serverId;
    data['server_start'] = this.serverStart;
    data['server_start_iso8601'] = this.serverStartIso8601;
    if (this.source != null) {
      data['source'] = this.source.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Source {
  String audioInfo;
  int bitrate;
  String genre;
  int iceBitrate;
  int iceChannels;
  int iceSamplerate;
  int listenerPeak;
  int listeners;
  String listenurl;
  String serverDescription;
  String serverName;
  String serverType;
  String serverUrl;
  String streamStart;
  String streamStartIso8601;
  String title;
  Null dummy;
  int audioBitrate;
  int audioChannels;
  int audioSamplerate;
  String subtype;

  Source(
      {this.audioInfo,
        this.bitrate,
        this.genre,
        this.iceBitrate,
        this.iceChannels,
        this.iceSamplerate,
        this.listenerPeak,
        this.listeners,
        this.listenurl,
        this.serverDescription,
        this.serverName,
        this.serverType,
        this.serverUrl,
        this.streamStart,
        this.streamStartIso8601,
        this.title,
        this.dummy,
        this.audioBitrate,
        this.audioChannels,
        this.audioSamplerate,
        this.subtype});

  Source.fromJson(Map<String, dynamic> json) {
    audioInfo = json['audio_info'];
    bitrate = json['bitrate'];
    genre = json['genre'];
    iceBitrate = json['ice-bitrate'];
    iceChannels = json['ice-channels'];
    iceSamplerate = json['ice-samplerate'];
    listenerPeak = json['listener_peak'];
    listeners = json['listeners'];
    listenurl = json['listenurl'];
    serverDescription = json['server_description'];
    serverName = json['server_name'];
    serverType = json['server_type'];
    serverUrl = json['server_url'];
    streamStart = json['stream_start'];
    streamStartIso8601 = json['stream_start_iso8601'];
    title = json['title'];
    dummy = json['dummy'];
    audioBitrate = json['audio_bitrate'];
    audioChannels = json['audio_channels'];
    audioSamplerate = json['audio_samplerate'];
    subtype = json['subtype'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['audio_info'] = this.audioInfo;
    data['bitrate'] = this.bitrate;
    data['genre'] = this.genre;
    data['ice-bitrate'] = this.iceBitrate;
    data['ice-channels'] = this.iceChannels;
    data['ice-samplerate'] = this.iceSamplerate;
    data['listener_peak'] = this.listenerPeak;
    data['listeners'] = this.listeners;
    data['listenurl'] = this.listenurl;
    data['server_description'] = this.serverDescription;
    data['server_name'] = this.serverName;
    data['server_type'] = this.serverType;
    data['server_url'] = this.serverUrl;
    data['stream_start'] = this.streamStart;
    data['stream_start_iso8601'] = this.streamStartIso8601;
    data['title'] = this.title;
    data['dummy'] = this.dummy;
    data['audio_bitrate'] = this.audioBitrate;
    data['audio_channels'] = this.audioChannels;
    data['audio_samplerate'] = this.audioSamplerate;
    data['subtype'] = this.subtype;
    return data;
  }
}
  

код, который я использовал, я довольно простой, это код, который я использовал.
если я проанализирую тот же код с простой структурой xml, это сработает, но при анализе icecast это не удастся.

пожалуйста, посоветуйте мне

 var JsonData = 'http://127.0.0.1:8000/status-json.xsl';
var parsedJson = json.decode(JsonData);
var title = Source.fromJson(parsedJson);
  

неверно ли форматирование json сервера icecast? он начинается с {

обновление 1

 class User {
  String title;

  User(Map<String, dynamic> data){
    title = data['title'];

  }
}
Future<Source> fetchData() async{
  var jsonData = 'http://online.doobeedoo.be:8000/status-json.xsl';
  final response =
      await http.get(jsonData); //wacht to de data is ontvangen (200)
  if(response.statusCode == 200)
  {
    var parsedJson = json.decode(response.body); //parsen van response
    var user = User(parsedJson);
    return('${user.title}'); //error here (A value of type 'String' can't be returned from function 'fetchData' because it has a return type of 'Future<Source>'.)
  }
  else
    {
      throw Exception('Failed to load status.json response file');
    }
}
  

Комментарии:

1. ключ, который я называю, — это источник: название

2. Вы пытаетесь выполнить синтаксический анализ 'http://127.0.0.1:8000/status-json.xsl' , который не является допустимым JSON.

3. Не могу ли я разобрать удаленный json?

4. Вы должны получить JSON, чего ваш код не делает. Но прямо сейчас вы анализируете 'http://127.0.0.1:8000/status-json.xsl' .

5. Вы имеете в виду, что полученный вами ответ соответствует тому, который вы указали выше (содержимое упомянутого вами файла json)?

Ответ №1:

Используйте http-пакет, чтобы отправить запрос на ваш сервер и получить ответ. Затем проанализируйте JSON так, как он у вас есть в настоящее время. В данный момент вы анализируете String URL. Не JSON.

 import 'package:http/http.dart' as http;

var url = 'http://127.0.0.1:8000/status-json.xsl';

var response = await http.get(url);//Actually get the data at the URL

var parsedJson = json.decode(response.body);//Parse the response
var title = Source.fromJson(parsedJson);
  

Комментарии:

1. если я сделаю это, я получу эту ошибку A value of type 'String' can't be returned from function 'fetchData' because it has a return type of 'Future<Source>'. я обновлю приведенный выше код до того, что я изменил

2. @AlainSeys Потому что вы полностью пренебрегли использованием своего собственного fromJson конструктора. Ошибка довольно ясна в отношении проблемы. Вы должны объяснять, чего вы не понимаете в проблеме, а не ожидать, что код будет написан только для того, чтобы исправить это для вас.

3. что я получаю об ошибке, так это то, что строка не может быть назначена внутри функции fetchData, пока я установил заголовок строки в своем классе user, поэтому, если я вызываю : user.title, это должно привести к данным?

4. @Alain тебе нужно уточнить это последнее утверждение

5. @AlainSeys Future<String>