为什么我的jsondecode()方法在flutter中抛出格式异常?

发布于 2025-01-19 08:53:40 字数 3794 浏览 2 评论 0原文

我已经学习 Flutter 移动开发有一段时间了,目前正在尝试构建一个单页文本翻译应用程序,以供练习。我尝试整合一个 Google 翻译 API

由于我用来提取翻译结果 json 对象(Post 方法 HTTP 请求)的 jsonDecode() 方法中出现错误(格式异常),我在运行应用程序时遇到问题

这是我的主屏幕代码

import 'package:flutter/material.dart';
import '../models/input_model.dart';

class HomePage extends StatefulWidget {
  HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  TextEditingController textController = TextEditingController();

  final translation = Sentence();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Translation App')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

////////////// Widget for the translation source text //////////////

            Container(
                width: MediaQuery.of(context).size.width / 1.5,
                child: TextField(
                  controller: textController,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(8)))),
                )),

////////////////////////////////////////////////////////////////////

            ElevatedButton(
                onPressed: () {
                  Sentence.connectToAPI('en', 'de', textController.text); //static language option
                  setState(() {});                                        //input for testing
                },
                child: Text('Translate')),

////////////// Widget for the translation result text //////////////

            Container(
                width: MediaQuery.of(context).size.width / 1.5,
                child: Text((translation.trans == null)
                    ? 'no data'
                    : translation.trans.toString())),
          ],
        ),
      ),
    );
  }
}

这是出现问题的模型文件谎言:

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

class Sentence {
  Sentence({
    this.trans,
    this.orig,
    this.backend,
  });

  String? trans;
  String? orig;
  int? backend;

  factory Sentence.fromJson(Map<String, dynamic> json) => Sentence(
        trans: json["trans"],
        orig: json["orig"],
        backend: json["backend"],
      );

  Map<String, dynamic> toJson() => {
        "trans": trans,
        "orig": orig,
        "backend": backend,
      };

  static Future<Sentence> connectToAPI(
      String from, String to, String text) async {
    String pathURL =
        'https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e';
    var response =
        await http.post(Uri.parse(pathURL), headers: <String, String>{
      'Content-Type': 'application/x-www-form-urlencoded',
      'User-Agent': 'PostmanRuntime/7.29.0'
    }, body: {
      'sl': from,
      'tl': to,
      'q': text
    });
    var jsonObject = jsonDecode(response.body); //the exception error message pointed here
    var textObject = (jsonObject as Map<String, dynamic>)['sentences'];

    return Sentence.fromJson(textObject);
  }
}

异常错误消息是:

FormatException(FormatException:意外字符(位于字符1)

^

我仍然是新手,这真的让我很困惑。我尝试在Google上搜索错误消息的解释,但仍然有很难理解这里的问题是什么?

I've been learning mobile development on Flutter for a while and currently trying to build a single-page text translation app, for exercise. I tried to integrate a Google Translate API.

I'm having trouble running the app due to an error (Format Exception) in the jsonDecode() method I use to extract the translation result json object (Post method HTTP request)

Here's my home screen code

import 'package:flutter/material.dart';
import '../models/input_model.dart';

class HomePage extends StatefulWidget {
  HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  TextEditingController textController = TextEditingController();

  final translation = Sentence();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Translation App')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

////////////// Widget for the translation source text //////////////

            Container(
                width: MediaQuery.of(context).size.width / 1.5,
                child: TextField(
                  controller: textController,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(8)))),
                )),

////////////////////////////////////////////////////////////////////

            ElevatedButton(
                onPressed: () {
                  Sentence.connectToAPI('en', 'de', textController.text); //static language option
                  setState(() {});                                        //input for testing
                },
                child: Text('Translate')),

////////////// Widget for the translation result text //////////////

            Container(
                width: MediaQuery.of(context).size.width / 1.5,
                child: Text((translation.trans == null)
                    ? 'no data'
                    : translation.trans.toString())),
          ],
        ),
      ),
    );
  }
}

And here's the model file where the problem lies:

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

class Sentence {
  Sentence({
    this.trans,
    this.orig,
    this.backend,
  });

  String? trans;
  String? orig;
  int? backend;

  factory Sentence.fromJson(Map<String, dynamic> json) => Sentence(
        trans: json["trans"],
        orig: json["orig"],
        backend: json["backend"],
      );

  Map<String, dynamic> toJson() => {
        "trans": trans,
        "orig": orig,
        "backend": backend,
      };

  static Future<Sentence> connectToAPI(
      String from, String to, String text) async {
    String pathURL =
        'https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e';
    var response =
        await http.post(Uri.parse(pathURL), headers: <String, String>{
      'Content-Type': 'application/x-www-form-urlencoded',
      'User-Agent': 'PostmanRuntime/7.29.0'
    }, body: {
      'sl': from,
      'tl': to,
      'q': text
    });
    var jsonObject = jsonDecode(response.body); //the exception error message pointed here
    var textObject = (jsonObject as Map<String, dynamic>)['sentences'];

    return Sentence.fromJson(textObject);
  }
}

The exception error message was:

FormatException (FormatException: Unexpected character (at character 1)

^

I'm still a newbie and it really confuses me. I tried to search for the explanation of the error message on Google but still having a hard time understanding it. What seems to be the problem here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文