设置从第三方对象序列化的JSON属性的顺序

时间:2015-12-19 02:07:18

标签: c# json json.net

我将对象序列化为JSON,而我没有代码(因此我无法在每个属性上设置[JsonProperty(Order = x)]属性)。

我还需要仅指定要序列化的某些属性。

以下代码正常运行,但我还需要指定属性的顺序。

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",
}

2 个答案:

答案 0 :(得分:2)

虽然JSON spec在技术上将对象定义为&#34;一组无序的名称/值对&#34;,但JSON.net仍允许您根据需要设置属性的顺序。在解析器中,您只需要在每个Order上设置JsonProperty值,然后相应地将它们排序。

protected override IList<JsonProperty> CreateProperties(Type type, Newtonsoft.Json.MemberSerialization memberSerialization)
{
    IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization)
        .Where(p => _propertiesToSerialize.Contains(p.PropertyName)).ToList();

    foreach (JsonProperty prop in properties)
    {
        prop.Order = _propertiesToSerialize.IndexOf(prop.PropertyName) + 1;
    }

    return properties.OrderBy(p => p.Order).ToList();
}

工作演示:https://dotnetfiddle.net/OhfWHl

答案 1 :(得分:0)

属性的顺序没有意义或在JSON中维护,原因相同,属性的顺序不在XML ...或Javascript本身中维护。如果您想要订购,则必须将其序列化为列表。