我正在创建一个可获取信息并从网站下载电影的应用程序。我已经成功地将信息设置在不同的数组中,并将它们组合成1个数组。
但是,现在我正在尝试将该数组放入一个更大的数组中(想与JSON一起使用),但是失败了。
我当前的Json输出如下:
{"moviedata":
["http:/xxxx","title title ","k0X0HrYtMm5u"],"tags":
["x","x","x","Prop","x","x","x","x","x","x","x"],"categorydata":
["x","x","x"]}
使用以下代码可以实现以下目的:
Dictionary<string, string[]> movie = new Dictionary<string, string[]>();
moviedata.Add("moviedata", moviegenerala);
moviedata.Add("tags", tagsa);
moviedata.Add("categorydata", categoriesa);
string moviejson = JsonConvert.SerializeObject(moviedata);
我想在此之上添加另一层,因此有一个名为“电影”的常规选项卡,对于每部电影,它都具有此信息。我该怎么办?
更新: 添加了以下代码:
var myShape = new
{
Movie = new Dictionary<string, string[]>
{
["moviedata"] = moviegenerala,
["tags"] = tagsa,
["categorydata"] = categoriesa,
["localdata"] = localdataa
}
};
var moviejson = JsonConvert.SerializeObject(myShape);
JSON似乎是正确的,但无法解析,因为它在第一个列表之后表示右括号后有文本。
更新: 将代码更改为此:
Dictionary<string, string[]> movies = new Dictionary<string, string[]>();
var myShape = movies.Select(m => new
{
Movie = new Dictionary<string, string[]>
{
// TODO - you'll need to get the appropriate data for this movie
["moviedata"] = moviegenerala,
["tags"] = tagsa,
["categorydata"] = categoriesa,
["localdata"] = localdataa
}
});
var moviejson = JsonConvert.SerializeObject(myShape);
File.AppendAllText("moviedata.txt", moviejson);
但是现在它只给出了空括号:(
答案 0 :(得分:0)
如果这是一次性序列化,那么最简单的方法就是将Dictionary用匿名类包装,并添加额外的属性缩进,例如
var myShape = new
{
Movie = new Dictionary<string, string[]>
{
["moviedata"] = moviegenerala,
["tags"] = tagsa,
["categorydata"] = categoriesa
}
};
var moviejson = JsonConvert.SerializeObject(myShape);
但是,如果在代码中的多个位置都需要相同的形状,那么我建议您为“形状”创建一个完整的类。
编辑:
上面产生的json是
{
"Movie": {
"moviedata": [ "http:/xxxx", "title title ", "k0X0HrYtMm5u" ],
"tags": [ "x", "x", "x", "Prop", "x", "x", "x", "x", "x", "x", "x" ],
"categorydata": [ "x", "x", "x" ]
}
}
如果您需要映射多个电影,然后进行投影,则可以使用.Select
:
// TODO : Replace this with your actual current movies
var inMovies = new[] {new Movie{...},new Movie {...}, ...};
var myShape = inMovies.Select(m => new
{
Movie = new Dictionary<string, string[]>
{
// TODO - you'll need to get the appropriate data for this movie, e.g. m.moviegenerala
["moviedata"] = moviegenerala,
...
}
});
产生以下内容:
[
{
"Movie": {
"moviedata": [ "http:/xxxx", "title title ", "k0X0HrYtMm5u" ],
"tags": [ "x", "x", "x", "Prop", "x", "x", "x", "x", "x", "x", "x" ],
"categorydata": [ "x", "x", "x" ]
}
},
{
"Movie": {
"moviedata": [ "http:/xxxx", "title title ", "k0X0HrYtMm5u" ],
"tags": [ "x", "x", "x", "Prop", "x", "x", "x", "x", "x", "x", "x" ],
"categorydata": [ "x", "x", "x" ]
}
}
]