Reputation: 228
The below snippet replicates a deserialisation issue I'm having inside a ServiceStack application. On running the below, the consignee property is populated correctly but the id is not.
static void Main (string[] args)
{
string json = "{\"@id\":\"abcd\",\"consignee\":\"mr mann\"}";
shipment some_shipment = new shipment();
some_shipment = json.FromJson<shipment>();
Console.Read();
}
class shipment
{
public string id { get; set; }
public string consignee { get; set; }
}
The library that is generating the JSON prefixes some elements with an @ to indicate that they came from an XML attribute but this program is beyond my control. I understand that ServiceStack name matches between JSON and object properties.
I've tried appending an @ to the property name but that doesn't help.
//doesn't help
public string @id { get; set;}
Is there a way of telling ServiceStack to deserialise @id into id without going through the process of implementing a custom deserialiser?
Upvotes: 2
Views: 76
Reputation: 21501
You need to use a [DataMember]
attribute to tell ServiceStack the name of the field to serialise into. When you do this you will be using a [DataContract]
which then requires that all other fields are marked with [DataMember]
to be included. I.e. they become opt-in.
So your Shipping
class becomes:
[DataContract]
class shipment
{
[DataMember(Name="@id")]
public string id { get; set; }
[DataMember]
public string consignee { get; set; }
}
You will need to reference using System.Runtime.Serialization;
I hope that helps.
Upvotes: 5