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

Solidity 0.8.9:uint转string是否可行?映射如何转指定JSON格式?

问题解答

问题1:Solidity中是否支持uint类型转换为string类型?

Solidity没有内置的直接转换函数,但可以通过自定义实现或者使用成熟库来完成转换。比如OpenZeppelin的Strings库(路径为@openzeppelin/contracts/utils/Strings.sol)提供了toString(uint256)方法,能直接将uint类型转为string。

问题2:修复GoTekERC721合约的details函数并返回指定格式字符串

原合约的details函数存在多个问题:无法直接返回mapping类型、声明的userBalances是未绑定的无效存储映射、未正确构造目标JSON格式字符串。以下是修复后的完整合约及说明:

修复后的合约代码

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol"; // 引入字符串转换库

contract GoTekERC721 is ERC721, Ownable {
    using Strings for uint256; // 让uint256类型直接调用toString方法

    constructor() ERC721("Go NFT", "GoN") {}

    // Owner to Phone
    mapping(address => uint256[]) public phones;
    // Phone to Balance
    mapping(uint256 => uint256) public balance;

    function register(uint256 phone, uint256 Balance) public {
        _mint(msg.sender, phone);
        phones[msg.sender].push(phone);
        balance[phone] = Balance;
    }

    function details(address owner) public view returns(string memory) {
        uint256[] memory ownerPhones = phones[owner];
        if (ownerPhones.length == 0) {
            return "{}"; // 无数据时返回空JSON
        }

        // 初始化JSON开头
        string memory result = "{";

        for (uint256 i = 0; i < ownerPhones.length; i++) {
            uint256 phone = ownerPhones[i];
            uint256 bal = balance[phone];

            // 拼接单个键值对:"phone":"balance"
            result = string(abi.encodePacked(result, '"', phone.toString(), '":"', bal.toString(), '"'));

            // 非最后一项时添加逗号分隔
            if (i != ownerPhones.length - 1) {
                result = string(abi.encodePacked(result, ","));
            }
        }

        // 补全JSON结尾
        result = string(abi.encodePacked(result, "}"));
        return result;
    }
}

关键修复说明

  • 引入OpenZeppelin的Strings库,通过using Strings for uint256简化uint到string的转换
  • 手动构造目标JSON格式:用abi.encodePacked拼接字符串片段,逐个处理手机号和对应余额,组装成{"phone":"Balance","phone":"Balance"}格式
  • 处理空数组边界情况,避免返回格式错误的JSON
  • 移除无意义的userBalances存储映射,直接遍历原数据拼接结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:05:29