Reputation: 1901
I have some classes in Windows Phone App:
[DataContract]
public class Function
{
[DataMember(Name = "params")]
public Params Parametrs { get; set; }
}
[DataContract]
public class Params
{
[DataMember(Name = "params1")]
public bool Params1 { get; set; }
[DataMember(Name = "params2")]
public string Params2 { get; set; }
[DataMember(Name = "params3")]
public MyClass Params3 { get; set; }
}
public string GetRequestString(Params parametrs)
{
Function func = new Function()
{
Parametrs = parametrs
};
string json = JsonConvert.SerializeObject(func);
return json;
}
Params params = new Params()
{
Params1 = true,
Params2 = "MyString",
Params3 = myClassObject,
}
var json = GetRequestString(params);
My problem that Params1
, Params2
, etc. can have different types. I can't define it in one class Params.
Can I pass a set of parameters, types, keys to the function and serialize it in JSON?
Is this possible with JsonConvert?
Upvotes: 0
Views: 659
Reputation: 19407
As c# is a strongly typed language, it requires that the type of a property be defined at compile time. However, if you need objects to dynamic, you can use the Object
base class. You may need to cast or convert them to relevant types before use however.
[DataContract]
public class Params
{
[DataMember(Name = "params1")]
public object Params1 { get; set; }
[DataMember(Name = "params2")]
public object Params2 { get; set; }
[DataMember(Name = "params3")]
public object Params3 { get; set; }
}
Params param = new Params()
{
Params1 = true,
Params2 = "MyString",
Params3 = new Object(),
};
var json = GetRequestString(param);
Upvotes: 2
Reputation: 2719
jsonconvert can serialize it here try property name to datamember Name="" eg:
[DataMember(Name = "Params1")]
public bool Params1 { get; set; }
Upvotes: 0