如何生成字典<>;对象
本文关键字:对象 gt lt 字典 何生成 | 更新日期: 2023-09-27 18:00:27
我想创建一个字典<>对象,而该dictionary对象应包含名称和值属性。例如:
Dictionary<string,object> dict = new Dictionary<string,object>();
当我将该字典序列化为json字符串时,它应该是这样访问的:
dict[0]["name"]=="ProductName"; //property name
dict[0]["value"]=="product1"; // value
dict[1]["name"]=="Description"; //property name
dict[2]["value"]=="product1 desc"; // value
............................
但我不知道该怎么做。有人能建议我怎么做吗?
编辑:-
事实上,我从Ajax帖子中得到了json字符串,如下所示:-
var str ="{"name":"firstName","value":"john"}",
一旦我得到它,我就会以以下格式反序列化该字符串:-
var dictDynamic = sear.Deserialize<dynamic>(str);
因此,我得到了这样的属性:
dictDynamic[0]["name"]
属性值如下:-
dictDynamic[0]["value"]
但现在的问题是,我想在服务器端这样做。Means希望以上述json字符串格式生成模型字符串,然后希望以上述方式进行反序列化。
字典不允许有两个值相同的键。所以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吗?让我们使用JSON.Net.
string json=JsonConvert.SerializeObject(products);
您可以使用JSON.NET
:
string json = JsonConvert.SerializeObject(dict);
但是您需要有一个有效的字典和可序列化的值。,例如:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };
dict["0"] = product;
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);