【问题标题】:How can I access the data inside the json如何访问 json 中的数据
【发布时间】:2020-10-18 13:49:33
【问题描述】:

这是我的 JSON 文件中的数据。

[
    {
        "id": "5",
        "msg": {
            "msg": "2121222",
            "sign": "אלמוג שטרית",
            "time": "26/6/2020 16:52",
            "title": "1212"
        }
    },
    {
        "id": "4",
        "msg": {
            "msg": "דשחדש",
            "sign": "אלמוג שטרית",
            "time": " ",
            "title": "בדיקה נ"
        }
    },
    {
        "id": "3",
        "msg": {
            "msg": "21",
            "sign": "אלמוג שטרית",
            "time": "",
            "title": "בדיקה חדשה"
        }
    },
    {
        "id": "2",
        "msg": {
            "msg": "בדיקה חדשה",
            "sign": "אלמוג שטרית",
            "time": "",
            "title": "בדיקה חדשה"
        }
    },
    {
        "id": "1",
        "msg": {
            "msg": "בדיקה",
            "sign": "",
            "time": "",
            "title": "בדיקה"
        }
    }
]

我使用 PHP 从什么数据库中提取这些数据。 php代码:

$stm = $conn->prepare($query);
$stm->execute();
$rows = $stm->fetchAll(PDO::FETCH_ASSOC);
$js = json_encode($rows, JSON_UNESCAPED_UNICODE);
print $js;

我的问题是如何将“msg”示例中包含的数据访问到“title”中。

我关于颤振的代码是:

List data;

  Future<String> getData() async {
    var response = await http.get(
        Uri.encodeFull("*myUrl*"),
        headers: {
          "Accept": "application/json"
        }
    );

    this.setState(() {
      data = json.decode(response.body);
    });

    print(data[0]["title"]);

    return "Success!";
  }

【问题讨论】:

  • 我很确定这一行: print(data[0]["title"]);应该这样写: print(data[0].title);
  • 试试print(data[0]['msg']['title']);这个必须打印1212

标签: php json flutter


【解决方案1】:

看看这个例子:

[
    {
        "id": "5",
        "msg": {
            "msg": "2121222",
            "sign": "אלמוג שטרית",
            "time": "26/6/2020 16:52",
            "title": "1212"
        }
    },
    {
        "id": "4",
        "msg": {
            "msg": "דשחדש",
            "sign": "אלמוג שטרית",
            "time": " ",
            "title": "בדיקה נ"
        }
    },
    {
        "id": "3",
        "msg": {
            "msg": "21",
            "sign": "אלמוג שטרית",
            "time": "",
            "title": "בדיקה חדשה"
        }
    },
    {
        "id": "2",
        "msg": {
            "msg": "בדיקה חדשה",
            "sign": "אלמוג שטרית",
            "time": "",
            "title": "בדיקה חדשה"
        }
    },
    {
        "id": "1",
        "msg": {
            "msg": "בדיקה",
            "sign": "",
            "time": "",
            "title": "בדיקה"
        }
    }
]

以下是您提供的 json 的模型类。

// To parse this JSON data, do
//
//     final yourModel = yourModelFromJson(jsonString);

import 'dart:convert';

List<YourModel> yourModelFromJson(String str) => List<YourModel>.from(json.decode(str).map((x) => YourModel.fromJson(x)));

String yourModelToJson(List<YourModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class YourModel {
    YourModel({
        this.id,
        this.msg,
    });

    String id;
    Msg msg;

    factory YourModel.fromJson(Map<String, dynamic> json) => YourModel(
        id: json["id"],
        msg: Msg.fromJson(json["msg"]),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "msg": msg.toJson(),
    };
}

class Msg {
    Msg({
        this.msg,
        this.sign,
        this.time,
        this.title,
    });

    String msg;
    String sign;
    String time;
    String title;

    factory Msg.fromJson(Map<String, dynamic> json) => Msg(
        msg: json["msg"],
        sign: json["sign"],
        time: json["time"],
        title: json["title"],
    );

    Map<String, dynamic> toJson() => {
        "msg": msg,
        "sign": sign,
        "time": time,
        "title": title,
    };
}

这是主界面

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:json_parsing_example/models.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _isLoading = false;
  List<YourModel> yourModel = List();

  Future<String> loadFromAssets() async {
    return await rootBundle.loadString('json/parse.json');
  }

  @override
  void initState() {
    super.initState();
    dataLoadFunction();
  }

  dataLoadFunction() async {
    setState(() {
      _isLoading = true;
    });

  /*   String jsonString = await loadFromAssets();
    // i have locally addded the data using the json file you can fetch the api over here.
    final yourdataModel = yourModelFromJson(jsonString);
    yourModel = yourdataModel;

    Instead of this you can use the below as the above is the sample example that i have created for you

    
     */


     /* 
     This is what you should do just add the url and its done.

      var response = await http.get(
        Uri.encodeFull("*myUrl*"),
        headers: {
          "Accept": "application/json"
        }
    );

     final yourdataModel = yourModelFromJson(response.body);
      yourModel = yourdataModel; 
     
      //just uncomment this code and add the url you are good to go.


    */

    setState(() {
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: _isLoading
            ? CircularProgressIndicator()
            : ListView.builder(
                itemCount: yourModel.length,
                shrinkWrap: true,
                itemBuilder: (BuildContext context, int index) {
                  return Card(
                    child: Column(
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.only(top: 10, left: 15),
                          child: Row(
                            children: <Widget>[
                              Text('Message :'),
                              Text(yourModel[index].msg.msg),
                            ],
                          ),
                        ),
                        Divider(
                          color: Colors.grey,
                        ),
                      ],
                    ),
                  );
                },
              ),
      ),
    );
  }
}

只需查看示例并告诉我它是否有效。

【讨论】:

  • 首先非常感谢!!抱歉,我有点不明白我对 Flutter 很陌生,但是如何放置 api 链接?
  • 我刚刚更新了代码,请检查一下,如果您有任何问题,请告诉我
  • 只需打勾,以便对其他人有所帮助。
【解决方案2】:

试试这个:

print(data['msg']['title'].toString());

或者这个:(如果上面的 Jason Data 不是列表)

print(data[0]['msg']['title'].toString());

【讨论】:

  • 您好,感谢您的回答。但是我收到以下错误消息:“未处理的异常:类型'String'不是'index'类型'int'的子类型”
  • 好的,我试过了,但没有成功。我改为: print (json.decode (data [0] ['msg']));它只是将数据打印给我,解码如何处理 msg 中的所有数据?
猜你喜欢
  • 1970-01-01
  • 2021-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多