如何使用三个参数将字典转换为json

时间:2018-01-12 14:52:48

标签: c# json dictionary

今天:

Table
address 1     zipcode    city
------------------------------
angel         123        and
candy         321        klj
mandy         874        jk3

目标:

object
    1
        address: xxxx
        zipcode: xxxx
        city:    xxxxx
    2
        address: xxxx
        zipcode: xxxx
        city:    xxxxx
    3
        address: xxxx
        zipcode: xxxx
        city:    xxxxx

如何使用c#将它从字典转换为json?

在字典中,你只能有两个参数

    Dictionary<string, string> aa1 = new Dictionary<string, string>();

    aa1.Add("angel", "123");
    aa1.Add("candy", "321");
    aa1.Add("mandy", "874");

    string myJsonString = (new JavaScriptSerializer()).Serialize(aa1);

谢谢!

2 个答案:

答案 0 :(得分:1)

你应该写一个代表你的实体(行)的类。类似的东西:

class Person
{
    [JsonProperty(PropertyName = "address 1")]
    public string Address1 { get; set; }

    [JsonProperty(PropertyName = "zipcode")]
    public int ZipCode { get; set; }

    [JsonProperty(PropertyName = "city")]
    public string City { get; set; }
}

然后你可以这样使用那个类:

var aa1 = new List<Person>();

aa1.Add(new Person()
{
    Address1 = "angel",
    ZipCode = 123,
    City = "and"
});

aa1.Add(new Person()
{
    Address1 = "candy",
    ZipCode = 321,
    City = "klj"
});

aa1.Add(new Person()
{
    Address1 = "mandy",
    ZipCode = 874,
    City = "jk3"
});

使用以下序列化它:

string json = JsonConvert.SerializeObject(aa1);
产生这个JSON的

[  
    {  
        "address 1":"angel",
        "zipcode":123,
        "city":"and"
    },
    {  
        "address 1":"candy",
        "zipcode":321,
        "city":"klj"
    },
    {  
        "address 1":"mandy",
        "zipcode":874,
        "city":"jk3"
    }
]

关于制作JSON的说明

不清楚(至少对我而言)你的JSON应该如何构建(例如包裹在一个对象中)。这是一种方式。

我还假设应该尊重表列的名称。每列都符合班级的每个属性。请注意,列address 1包含空格。 C#不允许带有空格的属性名称,因此我必须使用Newtonsoft.Json,它允许在序列化对象时设置自定义属性名称。 JavaScriptSerializer无法在编写自定义JavaScriptConverter之外重命名属性以进行序列化(但这是一个不同的故事)。

答案 1 :(得分:0)

请试试这个。

ar aa1 = new List<Dictionary<string, string>>();

var dict = new Dictionary<string, string>();

dict["address"] = "angel";
dict["zipcode"] = "123";
dict["city"] = "and";

aa1.Add(dict);

dict["address"] = "candy";
dict["zipcode"] = "321";
dict["city"] = "klj";

aa1.Add(dict);

dict["address"] = "mandy";
dict["zipcode"] = "874";
dict["city"] = "jk3";

aa1.Add(dict);

string myJsonString = (new JavaScriptSerializer()).Serialize(aa1);

Console.WriteLine(myJsonString);