C# 如何在c语言中生成Dictionary对象

C# 如何在c语言中生成Dictionary对象,c#,json,dictionary,C#,Json,Dictionary,我想创建一个Dictionary对象,该Dictionary对象应该包含 名称和值属性。例如: Dictionary<string,object> dict = new Dictionary<string,object>(); 但我不知道该怎么做。谁能建议我怎么做 编辑:- 实际上,我从Ajax帖子中得到的json字符串如下:- var str ="{"name":"firstName","value":"john"}", dictDynamic[0]["value"

我想创建一个Dictionary对象,该Dictionary对象应该包含 名称和值属性。例如:

Dictionary<string,object> dict = new Dictionary<string,object>();
但我不知道该怎么做。谁能建议我怎么做

编辑:-

实际上,我从Ajax帖子中得到的json字符串如下:-

var str ="{"name":"firstName","value":"john"}",
dictDynamic[0]["value"]
一旦我得到它,我将按以下格式反序列化该字符串:-

var dictDynamic = sear.Deserialize<dynamic>(str);
财产价值如下:-

var str ="{"name":"firstName","value":"john"}",
dictDynamic[0]["value"]
但问题是现在我想在服务器端这样做。这意味着我想以上述json字符串格式生成模型字符串,然后再以上述方式进行反序列化。

您可以使用:

但您需要有一个有效的字典和可序列化的值,例如:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };
dict["0"] = product;

字典不允许有两个值相同的键。因此,0作为键不起作用

也许最好的办法是创建一个对象来保存您的信息

public class Product
{
    public string ID {get;set;}
    public string Name {get;set;}
    public string Value {get;set;}
}
然后创建一些对象

Product product=new Product();
product.ID="0";
product.Name="My Super Widget";
product.Value="500";
//Then add that product to the dictionary.
Dictionary<string, Product> products=new Dictionary<string, Product>();
products.Add(product.ID, product);
//then you can access it in this way
products["0"].Name; //the value of this is "My Super Widget"

使用Json.NET之类的Json解析器,我的问题是,当我反序列化字符串时,我会得到键和值,但根据旧代码,我需要的是名称而不是键。那么我们怎么做呢?抱歉,但我不明白。你能不能把你的问题扩大一点,再解释一下,你到底想做什么?我想通过这种方式访问数据str[0][name]和str[0][value]Desearialization后。其中name是属性名称,value是该属性的值。并且不必使用字典。@Pawan您的问题特别询问如何在C中创建字典,然后如何将其序列化为JSON字符串。不幸的是,您发布的用于访问结果对象的语法无效。您还没有提供任何描述为什么要以这种方式访问对象的内容。也许你应该更新这个问题来清楚地解释你想要实现的目标。我已经更新了我的问题。我想这样做是因为应用程序的旧结构。我不能改变它。如果你解释你的代码以及它如何帮助OP,而不是仅仅将其转储到页面上,这会很有帮助。
Product product=new Product();
product.ID="0";
product.Name="My Super Widget";
product.Value="500";
//Then add that product to the dictionary.
Dictionary<string, Product> products=new Dictionary<string, Product>();
products.Add(product.ID, product);
//then you can access it in this way
products["0"].Name; //the value of this is "My Super Widget"
string json=JsonConvert.SerializeObject(products);
var myDict = new Dictionary<string, Dictionary<string, string>>();

var innerDict = new Dictionary<string, string>();
innerDict.Add("name", "name 0");
innerDict.Add("value", "value 0");

myDict.Add("0", innerDict);

innerDict = new Dictionary<string, string>();
innerDict.Add("name", "name 1");
innerDict.Add("value", "value 1");

myDict.Add("1", innerDict);

var foo = myDict["0"]["name"]; // returns "name 0"

string json = Newtonsoft.Json.JsonConvert.SerializeObject(myDict);