我有以下表格的数据:
{
"sections" : [
{
"section" : {
"Term" : "News",
"Term ID" : "4,253"
}
},
{
"section" : {
"Term" : "Sports",
"Term ID" : "4,254"
}
},
// ...
]
}
我想将它序列化为以下类的集合:
public class Section
{
public string Name;
public int Tid;
}
以下是我使用的代码,使用JSON.NET:
// e.Result is the downloaded JSON
JObject jsonData = JObject.Parse(e.Result);
var sections = jsonData["sections"].Select(obj => obj["section"]).Select(sectData => new Section()
{
Name = HttpUtility.HtmlDecode(sectData["Term"].Value<string>().Replace("\"", "")),
Tid = int.Parse(sectData["Term ID"].Value<string>().Replace(",", ""))
});
foreach (Section s in sections)
{
// _sections is an ObservableCollection<Section>
_sections.Add(s);
}
感觉有点笨重。我可以更优雅地做到这一点吗?
特别是foreach
循环结束。我宁愿使用addAll
或concat
之类的方法。
答案 0 :(得分:2)
有些事情......
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Section> sections = serializer.Deserialize<List<Sections>>(e.Result);
另请参阅DataContractJsonSerializer,它在技术上取代了JavaScriptSerializer,但在我尝试使用它时似乎总是很麻烦。
答案 1 :(得分:0)
在解析数字之前,您不必使用Replace
删除千位分隔符,Parse
方法只有在允许的情况下才能处理它们并确保它使用文化实际上有逗号为千位分隔符:
Tid = Int32.Parse(sectData["Term ID"].Value<string>(), NumberStyles.AllowThousands, CultureInfo.InvariantCulture)
如果_sections
变量是List<Section>
,那么您可以使用它的AddRange方法一次性添加它们:
_sections.AddRange(sections);
或者,如果列表仅包含这些项目,您可以从结果中创建列表,而不是先创建它,然后将项目添加到其中:
_sections = sections.ToList();
答案 2 :(得分:0)
我建议您在Select语句中重写匿名委托,如下所示:
var sections = jsonData["sections"].Select(obj => obj["section"]).Select(sectData =>
{
var section = new Section()
{
Name = HttpUtility.HtmlDecode(sectData["Term"].Value<string>().Replace("\"", `enter code here`"")),
Tid = int.Parse(sectData["Term ID"].Value<string>().Replace(",", ""))
};
_sections.Add(section);
return section;
});
请记住,lambdas可以形成闭包,因此_sections集合在传递给Select的委托中可用。这种方法应该摆脱foreach循环。