我將對象序列化爲JSON,但我沒有它的代碼(所以我不能在每個屬性上設置[JsonProperty(Order = x)]
屬性)。設置從第三方對象序列化的JSON屬性的順序
我還需要僅指定某些要序列化的屬性。
以下代碼正在工作,但我還需要指定屬性的順序。
public class DynamicContractResolver : Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver
{
private IList<string> _propertiesToSerialize = null;
public DynamicContractResolver(IList<string> propertiesToSerialize)
{
_propertiesToSerialize = propertiesToSerialize;
}
protected override IList<JsonProperty> CreateProperties(Type type, Newtonsoft.Json.MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization); //.OrderBy(p => p.Order).ToList();
return properties.Where(p => _propertiesToSerialize.Contains(p.PropertyName)).ToList();
}
}
//...
List<string> propertiesToSerialize = new List<string>(new string[]
{
"name",
"masterString",
"cruiseMode",
"account"
});
DynamicContractResolver contractResolver = new DynamicContractResolver(propertiesToSerialize);
string json = Newtonsoft.Json.JsonConvert.SerializeObject(_objToSerialize, Newtonsoft.Json.Formatting.Indented,
new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = contractResolver });
輸出是:
{
"masterString": "Provider...",
"cruiseMode": 2,
"account": "xxx\yyy",
"name": "AdWorksName"
}
但我需要它是:
{
"name": "AdWorksName",
"masterString": "Provider...",
"cruiseMode": 2,
"account": "xxx\yyy",
}
工作正常!還有這樣一個簡單的解決方案。感謝Brian! – bdog
沒問題;樂意效勞。 –