用于多个数据存储的ASP.NET命名空间控件,简单.ToJSON()

时间:2014-03-26 20:38:32

标签: c# asp.net json list hashtable

我需要存储List或Hashtable或类似的内容:

Element[542]["Title"] = "Some Title";
Element[542]["Html"] = "some Value";
Element[542]["CSS"] = "some class css";
Element[542]["SomethingElse"] = something else goes in here.

Element[621]["Title"] = "Title for 621";
Element[621]["Html"] = "Some Html value for 621";
Element[621]["CSS"] = "Some CSS Class";
Element[621]["SomethingElse"] = "something else goes in here."

如何创建这样的列表?如果我可以将它转换为基于数字值的json,那将是很好的,例如,621将是值,因此它只会获取该数字的那些并将其输出到JSON变量中,如下所示:< / p>

AddMoreJsonToThisVariable.621 = {

    Title : "Title for 621",
    Html : "Some Html value for 621",
    CSS :  "Some CSS Class",
    SomethingElse : "something else goes in here."
}

ASP.NET中是否有可用于生成此类列表的内容?或者某种方式做到这一点?可以将Hashtable插入到另一个Hashtable的第二个参数中吗?这可行吗?

1 个答案:

答案 0 :(得分:1)

我建议你创建一个班级。

public class MyClass
{
    public int Id {get; set;}
    public string Title {get;set;}
    public string Html {get;set;}
    public string CSS {get;set;}
    public string SomethingElse {get;set;}
}

//Then create a dictionary.
Dictionary<int, MyClass> MyDictionary=new Dictionary<int, MyClass)();
// create an some instance of MyClass
MyClass MyClassInstance=new MyClass(){Id=621, Title="A Title", Html="Some Html", CSS= "Some CSS", SomethingElse="Something else goes here"};
//add it to your dictionary
MyDictionary.Add(MyClassInstance.Id, MyClassInstance);
//serialize it to JSON with Json.Net
string somejson= JsonConvert.SerializeObject(MyDictionary);

如果要在输出时对其进行排序,请使用带有lambda表达式的OrderBy。

foreach(KeyValuePair<string, MyClass> kvp in MyDictionary.OrderBy(x => x.Key)
{
    Console.WriteLine("Key is: " + kvp.Key + " and Html is: " + kvp.Value.Html);
}

我假设字典是你想要的。如果没有,那么找出要使用的collection