【问题标题】:How to get a json data that model includes text json property in asp.net web api?如何在 asp.net web api 中获取模型包含文本 json 属性的 json 数据?
【发布时间】:2019-10-18 06:52:40
【问题描述】:

我的 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 格式。

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-web-api asp.net-core-mvc


    【解决方案1】:

    使用Newtonsoft library解析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"),
        };
    }
    

    【讨论】:

    • 我可以使用自定义 JsonConverter 吗?
    • 您可以使用JsonConvert.DefaultSettings = () =&gt; { return new JsonSerializerSettings() ; }; 定义自定义序列化程序并将转换器添加到设置中
    【解决方案2】:

    尝试使用以下代码返回 IEnumerable&lt;JObject&gt;,因为您在 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 core 3.0,需要添加对Microsoft.AspNetCore.Mvc.NewtonsoftJson的包引用并更新Startup.ConfigureServices调用AddNewtonsoftJson。

    services.AddMvc().AddNewtonsoftJson();
    

    更新:

    下面是使用Newtonsoft.JsonNewtonsoft.Json在asp.net core 3.0中使用自定义json转换器的demo;

    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;
    
        }
    

    【讨论】:

    • 这是一个很好的解决方案,但我可以使用自定义 JsonConverter 来实现吗?
    • @barteloma 好的,我为 App 模型创建了一个自定义 json 转换器,请参阅上面的更新代码演示。
    猜你喜欢
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 2021-05-02
    • 2012-08-29
    • 2019-11-18
    相关资源
    最近更新 更多