Note that there are some explanatory texts on larger screens.

plurals
  1. POBest approach to a class representing JSON with variable parameters in C#
    text
    copied!<p>I have a webservice in WCF whose operations require requests and responses in JSON format. I know that I can just write C# objects with properties that I want represented in JSON, but my problem is that the JSON parameters may change. For example, my method contract is the following:</p> <pre><code> [WebInvoke(Method = "PUT", UriTemplate = "users", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [OperationContract] Response PutUserAccount(User user); </code></pre> <p>User's parameters may contain any number of parameters, so an instance of User may be sometimes:</p> <pre><code>{ "Name" : "John", "LastName" : "Doe", "Email" : "jdoe@gmail.com", "Username" : "jdoe", "Gender" : "M" "Phone" : "9999999" } </code></pre> <p>or even:</p> <pre><code>{ "Name" : "John", "LastName" : "Doe", "Email" : "jdoe@gmail.com", "Username" : "jdoe", "FavoriteColor" : "Blue" } </code></pre> <p>What is the best approach to have an object with a mutable number of properties to represent a JSON document?</p> <p><strong>EDIT</strong> This class allowed me to have a flexible JSON representation, since I can't use a <code>JObject</code> with WCF (Should I post this as answer?):</p> <pre><code>using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace MyNamespace { [Serializable] public class Data : ISerializable { internal Dictionary&lt;string, object&gt; Attributes { get; set; } public Data() { Attributes = new Dictionary&lt;string, object&gt;(); } public Data(Dictionary&lt;string, object&gt; data) { Attributes = data; } protected Data(SerializationInfo info, StreamingContext context) : this() { SerializationInfoEnumerator e = info.GetEnumerator(); while (e.MoveNext()) { Attributes[e.Name] = e.Value; } } public void GetObjectData(SerializationInfo info, StreamingContext context) { foreach (string key in Attributes.Keys) { info.AddValue(key, Attributes[key]); } } public void Add(string key, object value) { Attributes.Add(key, value); } public object this[string index] { set { Attributes[index] = value; } get { if (Attributes.ContainsKey(index)) return Attributes[index]; else return null; } } } </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload