asp.net 如何在Model类中将字符串转换为JSON

yquaqz18  于 2022-11-19  发布在  .NET
关注(0)|答案(2)|浏览(165)

我想在接收来自API的值时将字符串转换为JSON。我正在从postman发送值,但无法将其转换为模型类中的JSON对象,我已使用自定义装饰器装饰了模型类。提前感谢。
这是模型类,我编写了自定义JSON转换器。

namespace WebApplication2.Models
   {
    [Serializable]
    public class Test
    {
        [JsonConverter(typeof(UserConverter))]
        public AS_AscContext AscParcelContext { get; set; }

    }
    public class AS_AscContext
    {
        public string ShellType { get; set; }
        public string LayoutName { get; set; }
    }

   
    public class UserConverter : JsonConverter
    {
        private readonly Type[] _types;

        public UserConverter(params Type[] types)
        {
            _types = types;
        }

        public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            JToken t = JToken.FromObject(value);

            if (t.Type != JTokenType.Object)
            {
                t.WriteTo(writer);
            }
            else
            {
                JObject o = (JObject)t;
                IList<string> propertyNames = o.Properties().Select(p => p.Name).ToList();

                o.AddFirst(new JProperty("Keys", new JArray(propertyNames)));

                o.WriteTo(writer);
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
        }

        public override bool CanRead
        {
            get { return false; }
        }

        public override bool CanConvert(Type objectType)
        {
            return _types.Any(t => t == objectType);
        }
    }

这是控制器接收值

[HttpPost]
    public IActionResult Privacy([FromBody]Test aS_AggregatorRequest)
    {
       
        return View();
    }

This is the postman collection

66bbxpm5

66bbxpm51#

尝试像这样更改您的postman JSON,

{
      "ascParcelContext": {
          "shellType": "ceme-sales-wallaby",
          "layoutName": "value"
     }
   }

不要转义任何JSON数据。

pengsaosao

pengsaosao2#

你的json里面有另一个json。所以最好修复api,但是如果你没有访问权限,试试这个

[HttpPost]
public IActionResult Privacy([FromBody]JObject jsonObject)
{

jsonObject["ascParcelContext"]= JObject.Parse( (string) jsonObject["ascParcelContext"]);

Test test = jsonObject.ToObject<Test>();

.....

}

public class Test
{
    [JsonProperty("ascParcelContext")]
    public AS_AscContext AscParcelContext { get; set; }

}
public class AS_AscContext
{
    [JsonProperty("shellType")]
    public string ShellType { get; set; }
    [JsonProperty("layoutName")]
    public string LayoutName { get; set; }
}

相关问题