You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Flutter中使用json_serializable转换JSON生成社交媒体ID对象可行吗?

在Flutter中用json_serializable实现指定JSON结构转换

完全可以用json_serializable实现这个转换,核心是通过自定义实体类和反序列化逻辑来映射字段结构,下面是具体实现步骤:

1. 添加依赖

在pubspec.yaml中添加相关依赖:

dependencies:
  json_annotation: ^4.8.1

dev_dependencies:
  build_runner: ^2.4.4
  json_serializable: ^6.7.0

2. 定义实体类

首先定义嵌套的Social类,对应目标JSON中的social对象:

import 'package:json_annotation/json_annotation.dart';

part 'social.g.dart';

@JsonSerializable()
class Social {
  final String instagram;
  final String facebook;

  Social({required this.instagram, required this.facebook});

  factory Social.fromJson(Map<String, dynamic> json) => _$SocialFromJson(json);
  Map<String, dynamic> toJson() => _$SocialToJson(this);
}

然后定义主实体类(比如命名为Profile),包含目标结构的所有字段,并自定义反序列化逻辑来适配原始JSON的结构:

import 'package:json_annotation/json_annotation.dart';
import 'social.dart';
import 'dart:convert';

part 'profile.g.dart';

@JsonSerializable()
class Profile {
  final String id;
  final String address;
  final Social social;

  Profile({required this.id, required this.address, required this.social});

  // 自定义反序列化:从原始JSON中提取字段并封装到Social对象
  factory Profile.fromJson(Map<String, dynamic> json) {
    return Profile(
      id: json['id'] as String,
      address: json['address'] as String,
      social: Social(
        instagram: json['instagram'] as String,
        facebook: json['facebook'] as String,
      ),
    );
  }

  // 序列化时自动生成目标结构的JSON
  Map<String, dynamic> toJson() => _$ProfileToJson(this);
}

3. 生成序列化代码

在终端运行以下命令,自动生成.g.dart文件:

flutter pub run build_runner build

4. 使用示例

// 原始输入JSON
final rawJsonStr = '''
{
  "instagram": "aaabb",
  "facebook": "cheche",
  "id": "abc12",
  "address": "asdfadf 123"
}
''';

// 反序列化原始JSON到Profile对象
final rawJsonMap = jsonDecode(rawJsonStr) as Map<String, dynamic>;
final profile = Profile.fromJson(rawJsonMap);

// 序列化Profile对象为目标结构的JSON
final targetJsonStr = jsonEncode(profile.toJson());
print(targetJsonStr);

运行后输出的JSON结构就是你需要的格式:

{
  "id": "abc12",
  "address": "asdfadf 123",
  "social": {
       "instagram": "aaabb",
       "facebook": "cheche"
  }
}

内容的提问来源于stack exchange,提问作者chichi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 19:52:45