0

I have a database table named "application" in my postgresql database.

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

my settings columnn has text type that includes json data as text format.

I am using this data in my asp.net web api application. The wab api can convert an object to a json data.

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

But my model includes a string property that has a json formatted data.

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

I want to get a json response like following:

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

all columns are converted to a json format.

2 Answers 2

1

Use Newtonsoft library to parse json and then add new properties

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"),
    };
}
Sign up to request clarification or add additional context in comments.

2 Comments

Can I do it using custom JsonConverter?
You can use JsonConvert.DefaultSettings = () => { return new JsonSerializerSettings() ; }; to define a custom serializer and add converters to settings
0

Try to use below code to return IEnumerable<JObject> since your keys in settings is dynamic.

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

Result:

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

If you use asp.net core 3.0, you need to add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson and update Startup.ConfigureServices to call AddNewtonsoftJson.

services.AddMvc().AddNewtonsoftJson();

Update:

Below is a demo to use custom json converter in asp.net core 3.0 with Newtonsoft.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();
    }
}

Model:

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

Controller:

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

    }

2 Comments

This is a good solution, but can I do it using custom JsonConverter?
@barteloma Ok,I create a custom json converter for the App model, see my update code demo above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.