zoukankan      html  css  js  c++  java
  • flutter 反序列化

    一、内联反序列化

    把JSON字符串转换成 Map<String, dynamic> 或者 List<dynamic>

    import 'dart:convert';
    
    main(List<String> args) {
      JsonCodec json = new JsonCodec();
    
      String str = '{"name":"tom"}';
      Map<String, dynamic> a = json.decode(str);
      print(a["name"]);
    
      String str1 = '["a","b"]';
      List<dynamic> b = json.decode(str1);
      print(b.length);
    
      String str3 = '{"name": "John Smith","email": "john@example.com"}';
      var c = json.decode(str3);
      print(c.runtimeType); //Map<String, dynamic>
    
      String str4 = '{"name": "John Smith","email": ["a","b"]}';
      var d = json.decode(str4);
      print(d.runtimeType); //Map<String, dynamic>
    
      String str5 = '{"name": "John Smith","email": {"a":"o","b":"p"}}';
      var e = json.decode(str5);
      print(e.runtimeType); //<String, dynamic>
    
    
      // String str6 = '{"name": "John Smith","email": {"a","b"}}';
      // var f = json.decode(str6); //FormatException: Unexpected character 报错
      // print(e.runtimeType);
    }

     复杂些的比如

    '{"age":19,"name":["tom","liu","wu"]}'    ??
     
     

    二、把字符串转成类对象

    import 'dart:convert';
    
    main(List<String> args) {
      String str = '{"age":19,"name":"tom"}';
      Map map = jsonDecode(str);
      Student user = Student.ds(map);
      print(user.age);
    }
    
    class Student {
      int age;
      String name;
      //Student(this.age, this.name);
      Student.ds(Map<String, dynamic> json)
          : age = json['age'],
            name = json['name'];
    }

    三、自动反序列化

    使用 json_serializable    https://pub.dev/packages/json_serializable

  • 相关阅读:
    第八章 多线程编程
    Linked List Cycle II
    Swap Nodes in Pairs
    Container With Most Water
    Best Time to Buy and Sell Stock III
    Best Time to Buy and Sell Stock II
    Linked List Cycle
    4Sum
    3Sum
    Integer to Roman
  • 原文地址:https://www.cnblogs.com/buchizaodian/p/13455036.html
Copyright © 2011-2022 走看看