Add the following using at the top of your service implementation class (make sure you also add the correct links to your project):
using Newtonsoft.Json; using System.Dynamic; using System.IO; using System.Text;
You can try this simple method that outputs a dynamic result:
public string GetData() { dynamic d = new ExpandoObject(); dynamic bartSimpson = new ExpandoObject(); dynamic lisaSimpson = new ExpandoObject(); bartSimpson.url = "foo"; bartSimpson.desc = "bar"; lisaSimpson.url = "foo"; lisaSimpson.desc = "bar"; d.userTypes = new ExpandoObject(); d.userTypes.BartSimpson = bartSimpson; d.userTypes.LisaSimpson = lisaSimpson; var s = JsonSerializer.Create(); var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) { s.Serialize(sw, d); } return sb.ToString(); }
To go one step further (you just need to pass Bart and Lisa as comaSeparatedNames ), you could do:
public string GetData(string comaSeparatedNames) { string[] names = comaSeparatedNames.Split(','); dynamic d = new ExpandoObject(); dynamic dNames = new ExpandoObject(); foreach (var name in names) { dynamic properties = new ExpandoObject(); properties.url = "foo"; properties.desc = "bar"; ((IDictionary<string, object>)dNames).Add(name, properties); } ((IDictionary<string, object>)d).Add("userTypes", dNames); var s = JsonSerializer.Create(); var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) { s.Serialize(sw, d); }
Note. I also provided lines (commented out) for deserialization.
source share