2017-03-07 15 views
0

まず、読んでいただきありがとうございます。さらに、私はあなたの助けが必要です!jsonに動的オブジェクトを追加する

ところで、私はNewtonsoft.Jsonを使用しています。

Console image

どのように私はこれに文字列を追加することができます。

obj.namedTypes.Menu.fields。 <文字列> =新しいExpandoObject();

だから私は、現時点ではこのコードを持っている:私はこのようなオブジェクトとして値を追加したい

internal class Program 
{ 
    private static void Main(string[] args) 
    { 
     Regex reg = new Regex(":addSubMenu\\((?<Description>.+),[a-z A-Z](\'|\")(?<Identifier>[a-zA-Z]+)(\'|\")\\)"); //Regular expression for finding the id and description i want. 

     dynamic obj = new ExpandoObject(); 

     obj.global = new ExpandoObject(); 
     obj.global.type = "table"; 
     obj.global.fields = new ExpandoObject(); 

     obj.global.fields.scriptConfig = new ExpandoObject(); 
     obj.global.fields.scriptConfig.type = "function"; 
     obj.global.fields.scriptConfig.args = new string[] {}; 
     obj.global.fields.scriptConfig.description = "a simple description"; 
     obj.global.fields.scriptConfig.returnTypes = new List<ExpandoObject>(); 

     dynamic arguments = new ExpandoObject(); 
     arguments.type = "ref"; 
     arguments.name = "Menu"; 
     obj.global.fields.scriptConfig.returnTypes.Add(arguments); 

     obj.namedTypes = new ExpandoObject(); 

     obj.namedTypes.Menu = new ExpandoObject(); 
     obj.namedTypes.Menu.type = "table"; 
     obj.namedTypes.Menu.fields = new ExpandoObject(); 

     Console.WriteLine(JsonConvert.SerializeObject(obj, Formatting.Indented)); 

     MatchCollection matches = reg.Matches(File.ReadAllText("test.txt")); 

     string description; 
     string value; 

     foreach (Match m in matches) 
     { 
      description = m.Groups["Description"].ToString(); 
      value = m.Groups["Identifier"].ToString(); 

      /* I want to add the value as a object like this: -> 
      * obj.namedTypes.Menu.fields.<value> = new ExpandoObject(); 
      * obj.namedTypes.Menu.fields.<value>.description = description; 
      */ 
      Console.WriteLine($"Description: {description}\nValue: {value}"); 
     } 
     Console.ReadLine(); 
    } 

: - >

  obj.namedTypes.Menu.fields.<value> = new ExpandoObject(); 

     obj.namedTypes.Menu.fields.<value>.description = description; 

答えて

1

は、辞書を使用してみてください。あなたの変更されたコードは次のようになり

-

//Initialization of Dictonary 
obj.namedTypes.Menu.fields = new Dictionary<string,string>(); 
//Reading from File and iteration on matches 
MatchCollection matches = reg.Matches(File.ReadAllText("test.txt")); 

string description; 
string value; 

foreach (Match m in matches) 
{ 
    description = m.Groups["Description"].ToString(); 
    value = m.Groups["Identifier"].ToString(); 
    obj.namedTypes.Menu.fields.Add(description , value); 
} 

//End: Serialize the Whole stuff 
Console.WriteLine(JsonConvert.SerializeObject(obj, Formatting.Indented)); 
関連する問題