我的 PHP/Mysql JSON 输出格式与 flutter 应用程序所需的示例 JSON 页面的格式不同

My PHP/ Mysql JSON output format is not the same format as sample JSON page as needed for a flutter app

提问人:The Mac 提问时间:9/22/2022 最后编辑:Slava RozhnevThe Mac 更新时间:10/13/2022 访问量:92

问:

所以我正在使用 flutter 应用程序从网页中提取 JSON。当我将应用程序指向:htttps://jsonplaceholder.typicode.com/posts 它 100% 工作时,输出如下(缩短):

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }
]

当我指向我自己的测试站点时,输出如下所示:

[{"userId":"1","id":"1","title":"TEST for Title","body":"Test for Body"},{"userId":"1","id":"2","title":"TEST for Title","body":"Test for Body"},{"userId":"1","id":"3","title":"TEST for Title","body":"Test for Body"},{"userId":"1","id":"4","title":"TEST for Title","body":"Test for Body"},{"userId":"1","id":"5","title":"TEST for Title","body":"Test for Body"},{"userId":"1","id":"6","title":"TEST for Title","body":"Test for Body"}]

PHP 代码如下所示:

 $sql = "select supplier_id as userId,  id, 'TEST for Title' as title, 'Test for Body' as body from sales_orders";
 $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

 $rows = $result->fetch_all(MYSQLI_ASSOC);

 header('Content-type: application/json');
  
 echo json_encode($rows);

我看到的唯一真正的区别是间距布局,整数周围没有“”。

砰地砸着我的头。

我可以在 flutter 控制台中打印我网站的输出,但它不会填充我的应用程序,因为字段名称完全相同,我只能假设是 JSON 格式导致了我的麻烦。

作为参考,我的飞镖代码(flutter)如下(https://www.geeksforgeeks.org/http-get-response-in-flutter/):

import 'dart:convert';

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
    return MaterialApp(
    home: HomePage(),
    );
}
}

//Creating a class user to store the data;
class User {
final int id;
final int userId;
final String title;
final String body;

User({
    this.id,
    this.userId,
    this.title,
    this.body,
});
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
//Applying get request.

Future<List<User>> getRequest() async {
    //replace your restFull API here.
    String url = "https://jsonplaceholder.typicode.com/posts";
    final response = await http.get(url);

    var responseData = json.decode(response.body);

    //Creating a list to store input data;
    List<User> users = [];
    for (var singleUser in responseData) {
    User user = User(
        id: singleUser["id"],
        userId: singleUser["userId"],
        title: singleUser["title"],
        body: singleUser["body"]);

    //Adding user to the list.
    users.add(user);
    }
    return users;
}

@override
Widget build(BuildContext context) {
    return SafeArea(
    child: Scaffold(
        appBar: AppBar(
        title: Text("Http Get Request."),
        leading: Icon(
            Icons.get_app,
        ),
        ),
        body: Container(
        padding: EdgeInsets.all(16.0),
        child: FutureBuilder(
            future: getRequest(),
            builder: (BuildContext ctx, AsyncSnapshot snapshot) {
            if (snapshot.data == null) {
                return Container(
                child: Center(
                    child: CircularProgressIndicator(),
                ),
                );
            } else {
                return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (ctx, index) => ListTile(
                    title: Text(snapshot.data[index].title),
                    subtitle: Text(snapshot.data[index].body),
                    contentPadding: EdgeInsets.only(bottom: 20.0),
                ),
                );
            }
            },
        ),
        ),
    ),
    );
}
}
php json flutter dart mysqli

评论

0赞 ADyson 9/22/2022
那么,当你把它指向你自己的URL并运行它时,在请求返回后,究竟包含什么?在那之前,你对发生的事情的描述非常好,但在那之后变得有点模糊。responseData
0赞 ADyson 9/22/2022
P.S. 我根本不知道 dart/flutter,但是如果某个东西是字符串(比如 JSON 中的 ID),它会很乐意自动将它们转换为整数,还是必须强制转换它们?只是大声想知道,在尝试将字符串值放入整数字段时,它是否可能在填充 User 对象时卡住了。stackoverflow.com/questions/13167496/......似乎建议您应该积极解析字符串。
0赞 Barmar 9/22/2022
布局在 JSON 中无关紧要。如果你想在 PHP 中添加它,请使用标志。带引号的数字是因为以字符串形式返回所有值。如果需要,您需要将它们转换为 PHP 中的整数。JSON_PRETTY_PRINTmysqli

答:

2赞 Slava Rozhnev 9/22/2022 #1

您可以使用标志来防止数字引号:JSON_NUMERIC_CHECK

$rows = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows,  JSON_NUMERIC_CHECK);

PHP代码在线