I have a C# Application.
I have a class that is generated from an xsd using xsd.exe. The class looks as follows
public class Transaction
{
public bool amountSpecified {get; set;}
public double amount {get; set;}
}
The following code shows an attempt at serialization
var transObj = new Transaction();
transObj.amount = 5.10;
var output =JsonConvert.Serialize(transObj);
The output string doesn't contain the amount field at all. It contains amountSpecified false which I don't want in my serialized json. However if I remove the amountSpecified field it works fine.
I have a huge set of classes and manually modifying each of them is a pain. My question is the following "Is there a way I can ignore all the fields with the PostFix "Specified" in Json.Net?" Or better still "Is it possible to generate c# class from xsd without the "Specified" postfix fields?"
I would be very glad if someone can point me in the right direction. Thanks in advance.
Add Custom resolver class like this
class CustomResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
if (prop.PropertyName.Contains("Specified"))
{
prop.ShouldSerialize = obj => false;
}
return prop;
}
}
Then Use it with JsonSerializerSettings. following code is the demo:
// Here is the container class we wish to serialize
Transaction pc = new Transaction
{
amountSpecified=true,
amount=23
};
// Serializer settings
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new CustomResolver();
settings.PreserveReferencesHandling = PreserveReferencesHandling.None;
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
settings.Formatting = Formatting.Indented;
// Do the serialization and output to the console
string json = JsonConvert.SerializeObject(pc, settings);
Console.WriteLine(json);
In addition to my post ( XSD tool appends "Specified" to certain properties/fields when generating C# code ) which you already found, here is another link about that topic: http://social.msdn.microsoft.com/Forums/en-US/ae260f91-2907-4f31-a554-74c8162b3b38/xsdexe-tool-creates-properties-with-specified-postfix
So from my experience your solutions are:
I guess that's not what you wanted to hear :-(
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.