美文网首页
flutter之json转换为DartBean(一条命令转换)

flutter之json转换为DartBean(一条命令转换)

作者: eliteTyc | 来源:发表于2019-09-26 09:34 被阅读0次
    步骤

    1.在项目根目录新建jsons文件夹并将json数据新建成为文件,在lib目录下新建包名为models
    注意:这两个文件夹的名字都必须为jsons和models

    image.png
    2.加入依赖
    dependencies:
    #    json生成model需要的依赖
      json_annotation: ^2.0.0
    
    dev_dependencies
    #    json生成model需要的依赖
      build_runner: ^1.0.0
      json_serializable: ^2.0.0
      json_model: ^0.0.2
    

    注意:这里添加完json_serializable相关依赖之后还添加了json_model的依赖,这就是快捷生成的关键,还有如果json中引用了其他model可以使用如下方式,具体可以查看官方地址json_model

    {
      "name":"wendux",
      "father":"$user", //可以通过"$"符号引用其它model类
      "friends":"$[]user", // 可以通过"$[]"来引用数组
      "keywords":"$[]String", // 同上
      "age":20
    }
    

    3.完成上面的操作之后
    在当前项目的根目录执行如下命令

    flutter packages pub run json_model
    

    控制太打印如下就成功了

    [INFO] Generating build script...
    [INFO] Generating build script completed, took 378ms
    
    [INFO] Creating build script snapshot......
    [INFO] Creating build script snapshot... completed, took 10.9s
    
    [INFO] Initializing inputs
    [INFO] Building new asset graph...
    [INFO] Building new asset graph completed, took 657ms
    
    [INFO] Checking for unexpected pre-existing outputs....
    [INFO] Checking for unexpected pre-existing outputs. completed, took 1ms
    
    [INFO] Running build...
    [INFO] 1.2s elapsed, 0/7 actions completed.
    [INFO] 2.2s elapsed, 2/7 actions completed.
    [INFO] 5.0s elapsed, 2/7 actions completed.
    [INFO] 6.7s elapsed, 5/7 actions completed.
    [INFO] Running build completed, took 7.0s
    
    [INFO] Caching finalized dependency graph...
    [INFO] Caching finalized dependency graph completed, took 62ms
    
    [INFO] Succeeded after 7.1s with 8 outputs (18 actions)
    
    ➜  github_client_app flutter packages pub run json_model
    [INFO] Generating build script...
    [INFO] Generating build script completed, took 440ms
    
    [INFO] Initializing inputs
    [INFO] Reading cached asset graph...
    [INFO] Reading cached asset graph completed, took 90ms
    
    [INFO] Checking for updates since last build...
    [INFO] Checking for updates since last build completed, took 832ms
    
    [INFO] Running build...
    [INFO] Running build completed, took 790ms
    
    [INFO] Caching finalized dependency graph...
    [INFO] Caching finalized dependency graph completed, took 43ms
    
    [INFO] Succeeded after 841ms with 4 outputs (4 actions)
    
    

    注意:如果json文件中加了注释可能会报错,需要删除注释,错误信息如下

    image.png

    相关文章

      网友评论

          本文标题:flutter之json转换为DartBean(一条命令转换)

          本文链接:https://www.haomeiwen.com/subject/privuctx.html