Reputation: 1418
I am having exactly the same problem as described here https://stackoverflow.com/questions/12565464/javascriptserializer-deserialize-an-identifier-with-space but as no one answered thought i'd try again,
API created by someone else in the form of
[{"AdvertId":"1234567","Price Original":"500","Sold":"False"}]
Application already uses a JavascriptSerilalization
to populate the named properties on many other API's so do not want to change that really, but my class to hold this data can not have a property with a space in it "Price Original", and this can't be removed or replaced with an _ or something. Are there any methods that can be called to translate the string to something different?
Is there any solution to this or have I got to use JSON.net to deserialize, was some bits on DataContracts I read up on and these might be able to help but I can't seems to find out how to get this to work for my code, and would be nice to know that is possible without investigation this path.
Sample Class
Class Sample
{
public int AdvertId { get; set; }
public string Price Original { get; set; }
public bool Sold { get; set; }
}
Upvotes: 2
Views: 1475
Reputation: 40393
You can still use built-in types, but you'll need to use DataContractJsonSerializer
instead of JavaScriptSerializer
, and add the appropriate DataContract
and DataMember
attributes - the implementation is a bit different, but still pretty straightforward.
One thing - your Sold
property is boolean, but your JSON sample has a string there - booleans are valid JSON types, so you can remove the quotes.
Some working code:
JSON:
[{"AdvertId":"1234567","Price Original":"500","Sold":false}]
C#:
var ser = new DataContractJsonSerializer(typeof(Sample[]));
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(JSON))) {
Sample[] s = (Sample[])ser.ReadObject(ms);
}
[DataContract]
public class Sample {
[DataMember]
public int AdvertId { get; set; }
[DataMember(Name = "Price Original")]
public string PriceOriginal { get; set; }
[DataMember]
public bool Sold { get; set; }
}
Upvotes: 4