.net 反序列化对象时发生Json转换为对象错误

hivapdat  于 2023-02-06  发布在  .NET
关注(0)|答案(1)|浏览(202)

我将json转换为对象并得到此错误

Newtonsoft.Json.JsonSerializationException: 'Error converting value "{"mid":"2","phone":"0965403801","requestId":"1585970510.732827","bankHubToken":"eyJ0aW1lc3RhbXAiOiIxNjMzNDE4NzgyNzQ0IiwidG9rZW4iOiI5NWJmYWM3OC00YmY3LTQyM2MtYjAxNS00NTNjMjkzYzk1ZWEiLCJzaWduIjoiLzVrcTg2dWdReFUvQ1daWCt2TERSaGhvaXN1VC9hS1JpejEwUGtTU0dxUVx1MDAzZCJ9","userName":"1392H46"}" to type 'OBBE.DGBIZ.API.Model.DataFieldUploadFile'. Path '', line 1, position 305.'

我的代码

var data = context.ActionArguments["data"];

if (data == null)
{
  context.Result = new OkObjectResult(

    new ErrorResponseMessage() { context = new ContextResponse(false, new List<string>() { APPID, HANDER_ERRORCODE.ERR_REQUEST_CONTENT.ToString(), "Request null" }, new ContextRequest("", ""), ResultConstants.ERROR_CODE_FAIL, "Request null") });

  return;
}

try
{
  String x = JsonConvert.SerializeObject(data);

  data = JsonConvert.DeserializeObject<DataFieldUploadFile>(JsonConvert.SerializeObject(data));
}

我的班级

public class DataFieldUploadFile
{
  public String? mid { get; set; }
  public String? requestId { get; set; }
  public String? phone { get; set; }
  public String? bankHubToken { get; set; }
  public String? userName { get; set; }
}

我试过了,但是不行。

h5qlskok

h5qlskok1#

试试这个

DataFieldUploadFile data = context.ActionArguments["data"] as DataFieldUploadFile;

如果数据为空,则意味着数据可能已经是一个JSON字符串,并尝试对其进行双重序列化。
所以你真的需要这个代码

string json = context.ActionArguments["data"]?.ToString();

if (!string.IsNullOrEmpty(json))
{
var data = JsonConvert.DeserializeObject<DataFieldUploadFile>(json);
}
else ... you another code

相关问题