Flutter json字符串与实体类转换

例子如下:

例子中json字符串涉及简单的类型,数组类型

import 'dart:convert';
import 'dart:io';
import 'dart:async';


main(){
     String jsonstr='{"name":"test","age":10,"friend":[1,2,3,4],"house":[{"addr":"qingdao","size":130},{"addr":"beijing","size":108}],"car":{"count":2}}';
     var tt=json.decode(jsonstr);
     print(json.encode(tt));
     AA zz=AA.fromJson(json.decode(jsonstr));
     print(zz);

}

class  AA
{

  String name;
  int    age;
  List<int> friend;
  List<BB>  house;
  CC car;
  AA.fromJson(Map<String,dynamic> jsonstr)
  {
    this.name=jsonstr["name"];
    this.age=jsonstr["age"];
    var x=jsonstr["friend"].map((i) => i).toList();
    this.friend=new List<int>.from(x);

    
    var xx=jsonstr["house"].map((i) => (BB.fromJson(i))).toList();
    this.house=new List<BB>.from(xx);

    this.car=CC.fromJson(jsonstr["car"]);
  }
}

class  BB
{
    String addr;
    int    size;
    BB.fromJson(Map<String,dynamic> jsonstr)
   {
    this.addr=jsonstr["addr"];
    this.size=jsonstr["size"];  
  }
}

class  CC
{
    int count;
    CC.fromJson(Map<String,dynamic> jsonstr)
   {
    this.count=jsonstr["count"];
  }
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flutter中,你可以使用`json_serializable`库和`json_annotation`库来将JSON字符串转换实体类。以下是一个简单的步骤: 1. 添加依赖: 在`pubspec.yaml`文件中添加以下依赖: ```yaml dependencies: json_annotation: ^4.4.0 dev_dependencies: build_runner: ^2.0.5 json_serializable: ^4.1.3 ``` 2. 创建实体类: 定义一个Dart类,使用`json_annotation`库的注解来指定JSON字段和Dart类属性之间的映射关系。例如: ```dart import 'package:json_annotation/json_annotation.dart'; part 'user.g.dart'; @JsonSerializable() class User { final int id; final String name; final String email; User({required this.id, required this.name, required this.email}); factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json); Map<String, dynamic> toJson() => _$UserToJson(this); } ``` 注意:在创建完实体类后,需要运行一次代码生成命令以生成相应的.g.dart文件。后面会提到。 3. 运行代码生成命令: 在终端中运行以下命令,生成.g.dart文件: ```bash flutter pub run build_runner build ``` 这将根据实体类中的注解生成对应的.g.dart文件。 4. 将JSON字符串转换实体类对象: 使用`json_serializable`库提供的fromJson方法,将JSON字符串转换实体类对象。例如: ```dart import 'dart:convert'; String jsonString = '{"id": 1, "name": "John", "email": "john@example.com"}'; Map<String, dynamic> json = jsonDecode(jsonString); User user = User.fromJson(json); ``` 现在,你就可以通过访问`user`对象的属性来获取JSON中的值了。 这就是将JSON字符串转换实体类的基本步骤。记得在每次修改实体类后,都要重新运行代码生成命令,以保持.g.dart文件的同步更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值