[英]ASP.NET MVC model binding - different names for JSON property and C# model properties
[英]ASP.NET MVC C# - Display class property names instead of the property names from JSON
在我使用 JsonPropertyAttribute 從 API 反序列化 JSON object 后遇到困難
我成功地從 JSON object
{
"property name": "property value"
}
但我的問題是,而不是像這樣顯示 class 屬性:
{
"propertyName": "property value"
}
我只看到我正在獲取的 JSON 的屬性名稱:
{
"property name": "property value"
}
有沒有一種簡單的方法可以讓它顯示 class object 的屬性名稱,而不是我獲取的 JSON 的屬性名稱?
編輯:
這是 class 的外觀:
public class JsonObjectDto {
[JsonProperty(PropertyName = "property name")]
public string propertyName { get; set; }
}
我做了類似於這個例子的事情:
public class HomeController : Controller {
public ActionResult Index() {
string jsonResponseString = "{\"property name\":\"property value\"}";
JsonObjectDto result = JsonConvert.Deserialize<JsonObjectDto>(jsonResponseString);
if(result != null) {
return Ok(result);
}
throw new Exception("fetch response error");
}
}
我希望實現的響應是使它像這樣 output:
{
"propertyName": "property value"
}
只需從 class 和反序列化 Object 之前刪除 JsonProperty 將“property name”替換為“propertyname”
public ActionResult Index()
{
string jsonResponseString = "{\"property name\":\"property value\"}";
jsonResponseString=jsonResponseString.Replace("property name","propertyName");
JsonObjectDto result = JsonConvert.Deserialize<JsonObjectDto>(jsonResponseString);
if(result != null) {
return Ok(result);
}
throw new Exception("fetch response error");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.