2016-02-01 58 views
1

我试图序列化一些的JSON API调用:C#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)

回答

2

我不知道,如果你可以做一些与dynamic类型或没有,但你肯定可以做一些与字典:

var obj = new 
{ 
    f5 = new Dictionary<string, object> 
    { 
     { 
      f5Name, new Dictionary<string, object> { 
       {poolName, memberState} 
      } 
     } 
    } 
} 
string postJson2 = JsonConvert.SerializeObject(obj); 
0

对于你打算做什么,你需要在合同解析器中解析你的名字。喜欢的东西:

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

的字典创建过程可以很容易自动化:-)