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

跨模型获取用户用户名时遭遇FormatException异常求助

解决UUID解析FormatException并获取用户名的方案

方案1:修改Django序列化器,直接返回用户名(最优)

既然需求是获取用户名,无需传递UUID再二次处理,直接在序列化阶段将用户名嵌入返回结果:

# Django 笔记序列化器示例
from rest_framework import serializers
from .models import Note

class NoteSerializer(serializers.ModelSerializer):
    # 直接关联用户表的username字段
    username = serializers.SlugRelatedField(source='user', read_only=True, slug_field='username')

    class Meta:
        model = Note
        # 替换原user字段为username,或同时保留
        fields = ['id', 'content', 'username', 'created_at']

修改后接口返回的JSON会包含"username": "xxx"字段,Flutter直接解析字符串即可,完全规避UUID解析问题。

方案2:修复Flutter端UUID解析逻辑

若必须保留UUID字段,需确保Flutter正确处理UUID字符串:

方式A:用String存储UUID

// Flutter Note模型类
class Note {
  final String id;
  final String content;
  final String userId; // 直接用String存储UUID字符串
  final String? username;

  Note({
    required this.id,
    required this.content,
    required this.userId,
    this.username,
  });

  factory Note.fromJson(Map<String, dynamic> json) {
    return Note(
      id: json['id'],
      content: json['content'],
      userId: json['user'], // 直接读取字符串,不做类型转换
      username: json['username'], // 若用方案1则添加
    );
  }
}

方式B:用UUID类型存储(需依赖uuid包)

  1. 添加依赖:flutter pub add uuid
  2. 模型类修改:
import 'package:uuid/uuid.dart';

class Note {
  final String id;
  final String content;
  final UuidValue userId;
  final String? username;

  Note({
    required this.id,
    required this.content,
    required this.userId,
    this.username,
  });

  factory Note.fromJson(Map<String, dynamic> json) {
    return Note(
      id: json['id'],
      content: json['content'],
      userId: UuidValue(json['user']), // 用UuidValue解析标准UUID字符串
      username: json['username'],
    );
  }
}

方案3:排查JSON格式合法性

打印接口返回的原始内容,确认user字段是标准UUID格式(如"user": "a1b2c3d4-5678-90ef-ghij-klmnopqrstuv"),无多余空格、引号或格式错误:

// Flutter中打印响应内容排查
print('Response Body: ${response.body}');

若格式异常,检查Django序列化器是否正确处理UUID字段(ModelSerializer默认会将UUID序列化为标准字符串,自定义序列化逻辑需确保输出格式正确)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:09:21