Dynamic objects in WCF not possible?

When building the response in WCF (json), I am sure that it is not possible to use fully dynamic objects, but first you need to double check here.

An ideal answer would look something like this:

"userTypes" : { "BartSimpson" : { "url" : "foo", "desc" : "bar" }, "LisaSimpson" : { "url" : "foo", "desc" : "bar" } } 

In the 'compiled' code, the above can be done by the following architecture (slightly pseudo-code):

 public class Character{ string url {get;set;} string desc{get;set;} } public class UserTypes{ public Character BartSimpson{get;set;} public Character LisaSimpson{get;set;} } 

But my main goal is that BartSimpson and LisaSimpson not compiled, so I could have any number of Character classes with any name / identifier in the response.

+6
source share
1 answer

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); } // deserializing sample //dynamic dummy = new ExpandoObject(); //var instance = s.Deserialize(new StringReader(sb.ToString()), // dummy.GetType()); //var foo = instance.userTypes.BartSimpson.url; return sb.ToString(); } 

Note. I also provided lines (commented out) for deserialization.

+5
source

Source: https://habr.com/ru/post/950067/


All Articles