C# 在web api中处理不同类型的JSON post请求
我的解决方案中有多个Json实体。例如:C# 在web api中处理不同类型的JSON post请求,c#,json,api,web,C#,Json,Api,Web,我的解决方案中有多个Json实体。例如: [DbName("school")] public class School { [JsonProperty("type")] public string Type{ get; set; } [JsonProperty("name")] public string Name{ get; set; } [JsonProperty("city")] public string City{ get; set;
[DbName("school")]
public class School
{
[JsonProperty("type")]
public string Type{ get; set; }
[JsonProperty("name")]
public string Name{ get; set; }
[JsonProperty("city")]
public string City{ get; set; }
}
[DbName("hospital")]
public class Hospital
{
[JsonProperty("type")]
public string Type{ get; set; }
[JsonProperty("name")]
public string Name{ get; set; }
[JsonProperty("city")]
public string City{ get; set; }
}
我有一个处理post请求的web api。请求以JSON而不是字符串的形式出现。我需要编写一个方法,处理所有请求,然后决定未来对象的json类型,如下所示:
[HttpPost]
public ActionResult CommonMethod(dynamic jsonObj)
{
if(jsonObj.Type == "health")
Hospital hospital = ConvertDynamicJson(jsonObj, hospital);
else if(jsonObj.Type == "education")
School school = ConvertDynamicJson(jsonObj, school);
...
}
我看到了很多关于动态json转换的示例,但几乎所有示例都使用字符串json数据
谢谢
请求以JSON而不是字符串的形式出现
我假设您正在尝试告知由动作选择器解析并作为对象传递的请求。它不再是Json格式的字符串
此外,您不能像这样确定动态对象。您可以合并模型,而不是尝试使用动态对象
public class CommonActionInput
{
public School School{ get; set; }
public Hospital Hospital{ get; set; }
}
您可以确定将哪个对象传递给操作
ActionResult CommonMethod(CommonActionInput input)
{
if(input.School != null)
{
}
if(input.Hospital != null)
{
}
}
请求以JSON而不是字符串的形式出现:JSON是一个具有特殊结构的字符串School和hospital总是空的。我必须将这些实体声明为json,以便能够在post方法中处理它们。或者为实体创建两个单独的操作。如何将一个类声明为Json到CommonActionInput类中?你能把答案写得更详细些吗?