我想在接收来自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();
}
2条答案
按热度按时间66bbxpm51#
尝试像这样更改您的postman JSON,
不要转义任何JSON数据。
pengsaosao2#
你的json里面有另一个json。所以最好修复api,但是如果你没有访问权限,试试这个