我正在尝试为API调用序列化一些JSON:
string f5Name = "MyBigIpName";
string poolName = "myPoolName";
string postJson2 = JsonConvert.SerializeObject(
new
{
f5 = new {
f5Name = new {
poolName = memberState
},
}
}
);
这将生成以下 JSON:
{
"f5": {
"f5Name": {
"poolName": {
"member": {
"address": "10.0.0.0",
"port": 80
},
"session_state": "STATE_DISABLED"
}
}
}
}
但是,我真正想做的是生成此 JSON:
{
"f5": {
"MyBigIpName": {
"myPoolName": {
"member": {
"address": "10.0.0.0",
"port": 80
},
"session_state": "STATE_DISABLED"
}
}
}
}
有没有办法让 f5Name 和 poolName 属性名称是动态的,以便我可以生成上述 JSON? 我正在使用Newtonsoft.JSON (JSON.NET)
我不确定您是否可以使用dynamic
类型做某事,但您肯定可以使用字典做一些事情:
var obj = new
{
f5 = new Dictionary<string, object>
{
{
f5Name, new Dictionary<string, object> {
{poolName, memberState}
}
}
}
}
string postJson2 = JsonConvert.SerializeObject(obj);
对于您的意图,您需要在合约解析器中解析您的姓名。像这样:
private class MyContractResolver : DefaultContractResolver
{
private Dictionary<string,string> _translate;
public MyContractResolver(Dictionary<string, string> translate)
{
_translate = translate;
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
string newPropertyName;
if(_translate.TryGetValue(property.PropertyName, out newPropertyName))
property.PropertyName = newPropertyName;
return property;
}
}
然后:
string f5Name = "MyBigIpName";
string poolName = "MyPoolName";
var _translator = new Dictionary<string, string>()
{
{ "f5Name", f5Name },
{ "poolName", poolName },
};
string postJson2 = JsonConvert.SerializeObject(
new
{
f5 = new {
f5Name = new {
poolName = memberState
},
},
new JsonSerializerSettings { ContractResolver = new MyContractResolver(_translator) });
如果使用 C# 6,则可以从nameof
中受益和/或使用字典初始化器使其更干净:
var _translator = new Dictionary<string, string>()
{
[nameof(f5Name)] = f5Name ,
[nameof(poolName)] = poolName ,
};
字典创建过程也可以轻松自动化:-)