I have a DataMember
that I need to be filled in by an api json string...
[DataContract]
public class Values
{
[DataMember]
public object value { get; set; }
}
API json string:
[
{
"type": "text",
"values": [
{
"value": "Text that is in textfield"
}
]
},
{
"type": "category",
"values": [
{
"value": {
"text": "Category title",
"color": "#000000"
}
}
]
}
]
I map this string to a strong typed object Field
like so:
private List<Field> PrepFieldObject(string response)
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(response)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Field>));
return (List<Field>)serializer.ReadObject(stream);
}
}
but when it gets to mapping Values.value
, it throws a hissy fit... I tried solving it like this:
[DataContract]
public class Values
{
[DataMember]
public object value
{
get {
return xamlValue;
}
set
{
xamlValue = new Value();
if( value is string )
{
xamlValue.text = (string)value; // This works fine
}
else
{
Value theValue = value as Value;
try
{
xamlValue.text = theValue.text; // Can't get hold of .text even though it does exist in the json.
xamlValue.color = theValue.color;
}
catch (Exception e)
{
}
}
}
}
public Value xamlValue { get; set; }
}
[DataContract]
public class Value
{
[DataMember]
public string text { get; set; }
[DataMember]
public string color { get; set; }
}
But it doesn't let me access properties of the object (I guess because they were never mapped by the DataContract)
I've tried adding
[KnownType(typeof(Value))]
[KnownType(typeof(string))]
but that doesn't help either :'(