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 :'(
I think you can use reflection to to access your object's property value. Try changing your setter's else part as
And the reflection method
You have to cast it to whatever type the
text
property belongs to.If you want a string or the defined string representation of the object use:
That is assuming that the other types (besides string) override the ToString() method to provide a meaningful string representation of the object.
Otherwise you would need to use:
You can just use the operator
is
, but you have to use it for each value thatvalue
can assume:You can read more about
is
here.You will have to use type-casting. Example string:
OR (preferably)
UPDATE:
When you are trying to serialize a JSON object and convert it to a strongly-typed object (something my ComplexType is an example of), its important to have the same names for the properties as is in the JSON. After serialization, you should be able to access the property values.
Hope this helps!!!
You COULD use a dynamic type:
More about Dynamics