简体   繁体   English

如何序列化 object 但给定属性仍序列化为字节数组?

[英]How can I serialize an object but have a given property remain serialized to a byte array?

I have the following ASP.NET Core Controller:我有以下 ASP.NET 核心 Controller:

using System.Text;
using Microsoft.AspNetCore.Mvc;

namespace FightClubApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProjectMayhemController : ControllerBase
    {
        [HttpGet]
        public Member Get() =>
            new Member
            {
                Name = "Robert Paulson",
                Code = ASCIIEncoding.ASCII.GetBytes("His name was Robert Paulson")
            };
    }

    public class Member
    {
        public string Name { get; set; }
        public byte[] Code { get; set; }
    }
}

Hitting that API endpoint (using GET https://localhost:5001/api/ProjectMayhem ) returns the following JSON:点击 API 端点(使用GET https://localhost:5001/api/ProjectMayhem )返回以下 JSON:

{
  "name": "Robert Paulson",
  "code": "SGlzIG5hbWUgd2FzIFJvYmVydCBQYXVsc29u"
}

However, I would like the Member.Code property to be serialized to a JavaScript Uint8Array .但是,我希望将Member.Code属性序列化为 JavaScript Uint8Array

I could convert the Base64 encoded JSON property back to a Uint8Array using something like:我可以使用以下方式将 Base64 编码的 JSON 属性转换回Uint8Array

code = new TextEncoder("utf-8").encode(atob(code));

, but I want to avoid doing it on the front-end. ,但我想避免在前端这样做。

Just realized I can sort of do this if I make Code a list of bytes ie刚刚意识到如果我让Code成为一个字节列表我可以做到这一点,即

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Mvc;

namespace FightClubApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProjectMayhemController : ControllerBase
    {
        [HttpGet]
        public Member Get() => new Member
        {
            Name = "Robert Paulson",
            Code = ASCIIEncoding.ASCII.GetBytes("His name was Robert Paulson")
                                      .ToList()
        };
    }

    public class Member
    {
        public string Name { get; set; }
        public List<byte> Code { get; set; }
    }
}

Hitting that API endpoint (using GET https://localhost:5001/api/ProjectMayhem ) returns the following JSON:点击 API 端点(使用 GET https://localhost:5001/api/ProjectMayhem )返回以下 JSON:

{
  "name": "Robert Paulson",
  "code": [
    72, 105, 115, 32, 110, 97, 109, 101, 32, 119, 97, 115, 32, 82, 111, 98, 101, 114, 116, 32, 80, 97, 117, 108, 115, 111, 110
  ]
}

I would just need to cast it to an Uint8Array .我只需要将它转换为Uint8Array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM