如何用C#将地址数据字典转换为多属性结构的JSON?
解决方法:用
List<Dictionary<string, string>>实现目标JSON结构 嘿,我明白你的需求了——你需要把表格里的三列数据转成包含多个对象的JSON数组,每个对象有address、zipcode、city三个属性,但目前只能用Dictionary<string, string>来处理对吧?
其实很简单,你可以把每一行数据封装成一个单独的Dictionary,然后把这些Dictionary放到一个List里,再序列化这个List就行。这样JavaScriptSerializer会自动把List转成JSON数组,每个Dictionary转成对应的JSON对象。
具体代码示例
// 创建一个存放Dictionary的列表,每个Dictionary对应一行数据 List<Dictionary<string, string>> dataList = new List<Dictionary<string, string>>(); // 处理第一行数据 Dictionary<string, string> row1 = new Dictionary<string, string>(); row1.Add("address", "angel"); row1.Add("zipcode", "123"); row1.Add("city", "and"); dataList.Add(row1); // 处理第二行数据 Dictionary<string, string> row2 = new Dictionary<string, string>(); row2.Add("address", "candy"); row2.Add("zipcode", "321"); row2.Add("city", "klj"); dataList.Add(row2); // 处理第三行数据 Dictionary<string, string> row3 = new Dictionary<string, string>(); row3.Add("address", "mandy"); row3.Add("zipcode", "874"); row3.Add("city", "jk3"); dataList.Add(row3); // 序列化整个列表 string myJsonString = new JavaScriptSerializer().Serialize(dataList);
最终生成的JSON结构
这段代码会输出你想要的格式:
[ {"address":"angel","zipcode":"123","city":"and"}, {"address":"candy","zipcode":"321","city":"klj"}, {"address":"mandy","zipcode":"874","city":"jk3"} ]
核心思路就是:单个Dictionary对应JSON里的一个对象,List对应JSON数组,两者结合正好匹配你的目标结构。这样既符合你只能用Dictionary<string, string>的限制,又能得到正确的输出。
内容的提问来源于stack exchange,提问作者HelloWorld1
相关产品推荐
相关产品推荐

