gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:50:53 25 4
gpt4 key购买 nike

我正在将对象序列化为我不拥有其代码的 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",
}

最佳答案

尽管 JSON spec从技术上讲,将对象定义为“一组无序的名称/值对”,JSON.net 仍然允许您根据需要设置属性的顺序。在您的解析器中,您只需在每个 JsonProperty 上设置 Order 值,然后按相应的顺序返回它们。

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

关于c# - 设置从第三方对象序列化的 JSON 属性的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34366528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com