2016-02-01 1 views
1

Je suis en train de sérialisation certains JSON pour un appel API:C# JSON de sérialisation anonyme

string f5Name = "MyBigIpName"; 
string poolName = "myPoolName"; 
string postJson2 = JsonConvert.SerializeObject(
    new 
    { 
     f5 = new { 
      f5Name = new { 
       poolName = memberState 
      }, 
     } 
    } 
); 

Il en résulte la JSON suivante:

{ 
    "f5": { 
     "f5Name": { 
      "poolName": { 
       "member": { 
        "address": "10.0.0.0", 
        "port": 80 
       }, 
       "session_state": "STATE_DISABLED" 
      } 
     } 
    } 
} 

Cependant, ce que je suis cherche vraiment à faire est de produire ce JSON:

{ 
    "f5": { 
     "MyBigIpName": { 
      "myPoolName": { 
       "member": { 
        "address": "10.0.0.0", 
        "port": 80 
       }, 
       "session_state": "STATE_DISABLED" 
      } 
     } 
    } 
} 

Est-il possible d'avoir les noms de propriété f5Name et poolName dynamique afin que je puisse produire le JSON ci-dessus? J'utilise Newtonsoft.JSON (JSON.NET)

Répondre

2

Je ne sais pas si vous pouvez faire quelque chose avec un type dynamic ou non, mais vous sûr peut faire quelque chose avec les dictionnaires:

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

Pour ce que vous avez l'intention, vous devez résoudre vos noms dans un résolveur de contrat. Quelque chose comme:

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

Et puis:

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

Si vous utilisez C# 6, vous pourriez bénéficier de nameof et/ou le rendre plus propre avec un intializer dictionnaire:

var _translator = new Dictionary<string, string>() 
{ 
    [nameof(f5Name)] = f5Name , 
    [nameof(poolName)] = poolName , 
}; 

Le processus de création de dictionnaire pourrait être automatisé facilement aussi :-)