如何获取模型在 Web API 中包含文本 json 属性 asp.net json 数据?



我的postgresql数据库中有一个名为"application"的数据库表。

id    name     settings
----------------------------------------------------------------
1     x        "{"color":"red", "left":"30px"}"
2     y        "{"menuSize":"4", "menuOrientation":"horizontal"}"

我的设置列具有文本类型,其中包含文本格式的 JSON 数据。

我正在我的 asp.net Web api 应用程序中使用此数据。wab api 可以将对象转换为 json 数据。

public class AppController : ApiController
{
App[] apps = new App[] 
{ 
new App { Id = 1, Name = "x" }, 
new App { Id = 2, Name = "y" }
};
public IEnumerable<App> GetApps()
{
return apps;
}
}

但是我的模型包含一个具有 json 格式数据的字符串属性。

public class AppController : ApiController
{
App[] apps = new App[] 
{ 
new App { Id = 1, Name = "x", Settings = "{"color":"red", "left":"30px"}" }
};
public IEnumerable<App> GetApps()
{
return apps;
}
}

我想得到如下所示的 json 响应:

[
{
id: 1,
name: "x",
color: "color",
left: "30px"
}
]

所有列都转换为 JSON 格式。

使用 Newtonsoft 库解析 json,然后添加新属性

public HttpResponseMessage  GetApps()
JObject jsonObject = JObject.Parse("{"color":"red", "left":"30px"}");
jsonObject.Add("id", 1);
jsonObject.Add("name", x);
return new HttpResponseMessage {
Content = new StringContent(jsonObject.ToString(Formatting.None), Encoding.UTF8, "application/json"),
};
}

尝试使用以下代码返回IEnumerable<JObject>,因为settings中的键是动态的。

public IEnumerable<JObject> GetApps()
{
var jsonList = new List<JObject>();
App[] apps = new App[]
{
new App { Id = 1, Name = "x", Settings = "{"color":"red", "left":"30px"}" },
new App { Id = 2, Name = "y", Settings = "{"menuSize":"4", "menuOrientation":"horizontal"}" }
};
foreach(var app in apps)
{
var obj = new JObject();
obj.Add("id", app.Id);
obj.Add("name", app.Name);
JObject settingsJsonObj = JObject.Parse(app.Settings);
foreach (var property in settingsJsonObj.Properties())
{
var name = property.Name;
obj.Add(name, settingsJsonObj.GetValue(name));                 
}
jsonList.Add(obj);
}
return jsonList;
}

结果:

[
{
"id": 1,
"name": "x",
"color": "red",
"left": "30px"
},
{
"id": 2,
"name": "y",
"menuSize": "4",
"menuOrientation": "horizontal"
}
]

如果使用 asp.net 核心 3.0,则需要添加对Microsoft.AspNetCore.Mvc.NewtonsoftJson的包引用,并更新Startup.ConfigureServices以调用 AddNewtonsoftJson。

services.AddMvc().AddNewtonsoftJson();

更新:

下面是在带有Newtonsoft.Jsonasp.net 核心 3.0 中使用自定义 json 转换器的演示;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
public class AppJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteStartObject();
{
writer.WritePropertyName("Id");
writer.WriteValue(value.GetType().GetProperty("Id").GetValue(value).ToString());
writer.WritePropertyName("Name");
writer.WriteValue(value.GetType().GetProperty("Name").GetValue(value).ToString());
var settings = value.GetType().GetProperty("Settings").GetValue(value);
JObject settingsJsonObj = JObject.Parse(settings.ToString());
foreach (var property in settingsJsonObj.Properties())
{
var name = property.Name;
writer.WritePropertyName(name);
writer.WriteValue(settingsJsonObj.GetValue(name));                  
}
}
writer.WriteEndObject();
}

public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

型:

[JsonConverter(typeof(AppJsonConverter))]
public class App
{
public int Id { get; set; }
public string Name { get; set; }
public string Settings { get; set; }
}

控制器:

//add `using Newtonsoft.Json;`
public IEnumerable<Object> GetApps()
{
App[] apps = new App[]
{
new App { Id = 1, Name = "x", Settings = "{"color":"red", "left":"30px"}" },
new App { Id = 2, Name = "y", Settings = "{"menuSize":"4", "menuOrientation":"horizontal"}" }
};
var jsonServices = JsonConvert.SerializeObject(apps);
var result = JsonConvert.DeserializeObject<List<Object>>(jsonServices);
return result;
}

最新更新