使用2个字符串属性填充字典属性

时间:2016-04-07 13:19:11

标签: c# json dictionary serialization

所以我有2个类型字符串(Name和Value)的属性,并希望将它们的值放入Dictionary属性,以及键值对。我可以在字典属性的getter中做到这一点吗?他们在同一个班级。

public string TagName { get; set; }

public string TagValue { get; set; }

public Dictionary<string, string> TagNameAndValue {get; set;}

Json输出:

      {
        "TagName": "processTime",
        "TagValue": "0"
      }

但我希望它是这样的:

      {
        "processTime": "0",            
      }

我知道这可能是一个不同的主题,对不起。

2 个答案:

答案 0 :(得分:1)

您无法使用属性TagNameTagValue在声明处初始化字典。

您可以使用构造函数中的那些字段初始化字典,如:

YourClassConstructor()
{
     TagNameAndValue = new Dictionary<string, string>() { {TagName, TagValue } };
}

使用C#6.0,您可以指定属性默认值,但您无法在属性初始化中使用类字段/属性。

如果您有一些常量字符串值,那么使用C#6.0可以执行以下操作:

public Dictionary<string, string> TagNameAndValue { get; set; } = 
                   new Dictionary<string, string>() { { "1", "3" } };

答案 1 :(得分:0)

使用名为newtonsoft.json的库

后,您可以获得所需的内容

在程序包管理器控制台中键入以下内容以安装nuget程序包:

install-package newtonsoft.json

可以使用JsonConvert.SerializeObject()静态方法解析字典。 JsonConvert位于Newtonsoft.Json命名空间。

Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("processTime", "25");
Console.WriteLine(JsonConvert.SerializeObject(dictionary));

您应该得到类似于:

的输出

enter image description here