如何将 SubTaskRuleRes.content 的列表反序列化为“<class 'str'>”,

How to deserialize a list to '<class 'str'>' for SubTaskRuleRes.content,

这是我对dto的定义class:

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace DeserializeDemo
{
    public class SubTaskRuleDto
    {
        public Guid Id { get; set; }

        [JsonConverter(typeof(ByteArrayConverter))]
        public byte[] Content { get; set; }

        public bool DisableImage { get; set; }

        public bool UseMobileAgent { get; set; }

        public bool SupplementEnable { get; set; }
    }

    public class ByteArrayConverter : JsonConverter<byte[]>
    {
        public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            short[] sByteArray = JsonSerializer.Deserialize<short[]>(ref reader);
            byte[] value = new byte[sByteArray.Length];
            for (int i = 0; i < sByteArray.Length; i++)
            {
                value[i] = (byte)sByteArray[i];
            }

            return value;
        }

        public override void Write(Utf8JsonWriter writer, byte[] value, JsonSerializerOptions options)
        {
            writer.WriteStartArray();

            foreach (var val in value)
            {
                writer.WriteNumberValue(val);
            }

            writer.WriteEndArray();
        }
    }
}

然后我将展示asp.net核心控制器代码:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;

namespace DeserializeDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class Clouds : ControllerBase
    {
        private readonly ILogger<Clouds> _logger;

        public Clouds(ILogger<Clouds> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public SubTaskRuleDto Get()
        {
            return new SubTaskRuleDto()
            {
                Id = Guid.NewGuid(),
                Content = new byte[] { 1, 7},
                DisableImage = false,
                UseMobileAgent = true,
                SupplementEnable = false,
            };
        }

        public enum ContentType
        {
            Xoml = 1,
            Python = 7,
            NodeJS = 8
        }
    }
}
api 运行良好,并在邮递员中测试正常: enter image description here

当我在 python 客户端中调用 api 时,我的代码是这样的:

# -*- coding:utf-8 -*-
import json
import deserialize
import requests


class SubTaskRuleRes:
    id: str
    content: str
    disableImage: bool
    useMobileAgent: bool
    supplementEnable: bool


def get_subtask_rule():
    url = "http://localhost:5000/clouds"
    res = requests.get(url)

    # print(res.content)
    # binary = res.content
    # output = json.loads(binary)

    my_instance = deserialize.deserialize(SubTaskRuleRes, res.json())
    print(my_instance)

get_subtask_rule()

反序列化- 1.8.3 - https://github.com/dalemyers/deserialize

问题是我无法将列表反序列化为“”或 SubTaskRuleRes.content.

的列表

deserialize不进行隐式类型转换。这就是你得到错误的原因(注意,总是 post 你得到的完整回溯)。

查看文档,您可以使用装饰器传递解析器函数(查看 Advanced Usage/Parsers,例如

import deserialize

@deserialize.parser("content", str)
class SubTaskRuleRes:
    id: str
    content: str
    disableImage: bool
    useMobileAgent: bool
    supplementEnable: bool
    

def get_subtask_rule():
    spam = {'id':'28631ee-abd', 'content':[1, 7],
            'disableImage': False, 'useMobileAgent':True,
            'supplementEnable': False}
    return deserialize.deserialize(SubTaskRuleRes, spam)

rule = get_subtask_rule()
print(rule.content)
print(type(rule.content))

输出

[1, 7]
<class 'str'>

注意,我不确定你为什么要 content 是列表文字,字符串