【问题标题】:Extract data from complex JSON in Flutter在 Flutter 中从复杂的 JSON 中提取数据
【发布时间】:2018-10-22 20:26:30
【问题描述】:

我正在从具有未知结构的更复杂的 JSON 中提取数据,它的结构随着操作而变化, JSON示例链接:http://afs-i.com/json.json

请在这里找到我的代码:http://afs-i.com/main.dart

提前致谢

更新: 我使用PHP代码提取数据,你可以在这里找到结果:http://afs-i.com/json.php

这是我的 PHP 代码:

$arraycars=array();
$y=json_decode($x);
//  echo "<pre>";
//  var_dump($y->tree[0]->children); 
foreach ($y->tree[0]->children as $f) {
  if(isset($f->vid)){
       global $arraycars;
       $arraycars[]=$f;
   } elseif(isset($f->children)){
     if(sizeof($f->children) > 0){
        coolectcars($f->children);
     }
    }   
   }
   function coolectcars($array){
   // var_dump($array);
   foreach ($array as $f) {
     if(isset($f->vid)){
        global $arraycars;
        $arraycars[]=$f;
     } elseif(isset($f->children)){
        if(sizeof($f->children) > 0){
            coolectcars($f->children);
        }
     }  
   }
  }
  echo json_encode($arraycars);

更新:2 我现在遇到此代码的空错误问题: 错误:

I/flutter ( 4264): NoSuchMethodError: The method 'forEach' was called on 
 null.
I/flutter ( 4264): Receiver: null
I/flutter ( 4264): Tried calling: forEach(Closure: (Children) => Null)

代码:

List<Children> cars = [];
Queue numQ = new Queue();
numQ.addAll(parsed["tree"][0]["children"]);
Iterator i = numQ.iterator;

while (i.moveNext()) {
//    print("ddddddd ${i.current}");
 if (i.current.containsKey("vid")) {
  cars.add(new Children(
      i.current['vid'], i.current['protocol'], i.current['datetime'],
      i.current['gpss']));
  } else {
  Queue numQ = new Queue();
  if (i.current["children"] != null) {
    numQ.addAll(i.current["children"]);
  //        iterate(numQ);
    List<Children> carse=[];
     carse = iterate(numQ);
     carse.forEach((data){
       cars.add(data);
     }) ;

   }
  }
 }
 cars.forEach((data) {
  print(data.toString());
 });
 List<Children> iterate(Queue numQ) {
 List<Children> cars=new List<Children>();
 Iterator i = numQ.iterator;
 while (i.moveNext()) {
 print("ddddddd ${i.current}");
 if (i.current.containsKey("vid")) {
  cars.add(new Children(
      i.current['vid'], i.current['protocol'], i.current['datetime'],
      i.current['gpss']));
  } else {
  if (i.current["children"] != null) {
    Queue numQ = new Queue();
    numQ.addAll(i.current["children"]);
    List<Children> carse=[];
    carse = iterate(numQ);
    carse.forEach((data){
      cars.add(data);
    }) ;
  }
  }
 return cars;
 } 
 }

【问题讨论】:

    标签: json dart flutter


    【解决方案1】:

    我更喜欢使用built_value 进行 json 反序列化/序列化。它更优雅。你不需要自己写下fromJsonbuilt_value 将为您生成反序列化器/序列化器。您可以查看built_value 的githubthisthis 文章。

    【讨论】:

    • 由于复杂性,我不得不使用自定义迭代迭代到 json。我使用了 Queue,但我遇到了空对象的问题
    • 你可以在 post 中找到 update:2,现在只有空值问题
    【解决方案2】:

    将 JSON 转换为 dart 的好地方here

    reddit url致敬

    只需将您的 json 复制到文本框中并生成,它会自动为您生成。

    有了这个,你可以调用fromJson 并输入json,然后你也可以自动完成它

    例如:用法

    final response =
            await http.get('http://afs-i.com/json.json');
    
    if (response.statusCode == 200) {
       final Autogenerated respJson = Autogenerated.fromJson(json.decode(response.body));
       print(respJson.tree[0].userId);
    }
    

    【讨论】:

    • 好。我看到它会有所帮助,但是转换器给了我多个类,如何将我的 json 提供给第一类(自动生成)并获取子对象列表。
    • fromJSON 接受 Map 作为参数,如果我没记错的话,当你得到响应时,你实际上可以将响应传递给该函数。
    • 你能检查一下我需要的帖子中的更新吗
    【解决方案3】:

    插入此import 'dart:convert'; 到顶部的小部件文件中。

    假设你有你的 json

    var response
    

    然后

    var jsonDecoded= json.decode(response);
    

    现在您可以像这样获取 name 和 user_id:

    var user_id= jsonDecoded["tree"][0]["user_id"];
    
    var name = jsonDecoded["tree"][0]["name"];
    

    注意:我从第一个对象(0 索引)中获取这些值。如果你想要每个对象的值,你可以循环获取它。

    【讨论】:

    • 循环结构不同,我需要循环输入(jsonDecoded["tree"][0]["children"])
    • 它是(对象(我需要)的数组,有时带有新的树数组)m 在循环时它崩溃,而元素是新的树数组
    • 嗨,如何检查值是否存在。像 PHP if (isset($name['tree'])) {...}
    【解决方案4】:

    我得到的最终答案:

    final parsed = json.decode(response.body);
    List<Children> cars = [];
    Queue numQ = new Queue();
    numQ.addAll(parsed["tree"][0]["children"]);
    Iterator i = numQ.iterator;
    
    while (i.moveNext()) {
      if (i.current.containsKey("vid")) {
    
        cars.add(new Children(
            i.current['vid'],
            i.current['datetime'],
           ));
    
    } else {
      Queue numQ = new Queue();
      if (i.current["children"].toString() != "[]") {
        numQ.addAll(i.current["children"]);
        List<Children> carse = [];
        carse = iterate(numQ);
        carse.forEach((data) {
          cars.add(data);
        });
      }
    }
    }
    
    
    List<Children> iterate(Queue numQ) {
    List<Children> cars = new List<Children>();
    Iterator i = numQ.iterator;
    while (i.moveNext()) {
    if (i.current.containsKey("vid")) {
      if (i.current.containsKey("vid")) {
    
        cars.add(new Children(
            i.current['vid'],
            i.current['datetime'],
           ));
    
    }
     } else {
      if (i.current["children"].toString() != "[]") {
      Queue numQ = new Queue();
      if (i.current["children"].toString() != "[]") {
        numQ.addAll(i.current["children"]);
        List<Children> carse = [];
        carse = iterate(numQ);
        carse.forEach((data) {
          cars.add(data);
        });
      }
      }
    }
     return cars;
     }
    

    【讨论】:

      猜你喜欢
      • 2019-12-03
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多