2

So I am using a flutter app to pull JSON from a webpage. When I point the app to: htttps://jsonplaceholder.typicode.com/posts it works 100% , the output is as follows (shortened):

[
  {
    "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"
  }
]

When I point to my own test site, the output is as follows:

[{"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"}]

The PHP code looks as follows:

 $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);

The only real difference I see is the spacing layout and the integers have no ""'s around them.

Thumping my head on this one.

I can print the output from my site in the flutter console, but it does not populate my app, as the field names are exactly the same, I can only assume its the JSON format thats causing my hassles.

For reference my dart code (flutter) is as follows (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),
                ),
                );
            }
            },
        ),
        ),
    ),
    );
}
}
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
The Mac
  • 93
  • 8
  • So, when you point this at your own URL and run it, what does `responseData` contain exactly, after the request returns? Your description of what happens was quite good up to that point, but got a little hazy after that. – ADyson Sep 21 '22 at 21:49
  • P.S. I don't know dart/flutter at all, but if something's a string (like the IDs in your JSON), will it happily convert them to integers automatically, or must you cast them? Just wondering aloud if maybe it's getting stuck populating your User object when trying to put string values into an integer field. https://stackoverflow.com/questions/13167496/how-do-i-parse-a-string-into-a-number-with-dart seems to suggest you ought to actively parse the string. – ADyson Sep 21 '22 at 21:52
  • The layout is irrelevant in JSON. If you want to add this in PHP, use the `JSON_PRETTY_PRINT` flag. The quoted numbers are because `mysqli` returns all values as strings. You'll need to convert them to integers in PHP if you need it. – Barmar Sep 21 '22 at 21:52

1 Answers1

2

You can use flag JSON_NUMERIC_CHECK for prevent number quotation:

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

php code online

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39