我已经在C#中反序列化了具有以下数据结构的JSON文件
[DataContract]
public class SentimentData
{
[DataMember(Name ="Column1")]
public IEnumerable<string> Column1 { get; set; }
[DataMember(Name ="Column-2")]
public IEnumerable<string> Column2 { get; set; }
}
column1的计数不等于column2的计数。我只想基本上转储第一列中column1的所有数据和第二列中column2的数据。我尝试了以下操作,但不起作用。
using (var writer = new StreamWriter(@"C:\test.csv"))
{
var nr = column1data.Select(y => new { Column1= y }).ToList();
//var nnr = column2data.Select(y => new { Column2 = y }).ToList();
var csv = new CsvWriter(writer);
csv.WriteRecords(nr);
//csv.WriteRecords(nnr);
writer.Flush();
}
任何人都可以知道该怎么做吗?
样本json:
{
"Negative": [
"a.txt",
"b.txt",
"a.txt",
"b.txt",
"a.txt",
"b.txt"
],
"Non-Negative": [
"a.txt",
"b.txt",
"a.txt",
"b.txt",
"a.txt",
"b.txt",
"a.txt",
"b.txt",
"a.txt",
"b.txt",
"a.txt",
"b.txt",
"a.txt",
"b.txt",
"a.txt",
"b.txt",
"a.txt",
"b.txt",
"a.txt",
"b.txt",
"a.txt",
"b.txt",
"a.txt",
"b.txt"
]
}
答案 0 :(得分:3)
遵循默认Enumerable.Zip
派生以下扩展名是为了允许压缩不等长的集合
public static class MyEnumerablExtensions {
public static IEnumerable<TResult> ZipOrDefault<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector) {
if (first == null) throw Error.ArgumentNull("first");
if (second == null) throw Error.ArgumentNull("second");
if (resultSelector == null) throw Error.ArgumentNull("resultSelector");
using (IEnumerator<TFirst> e1 = first.GetEnumerator()) {
using (IEnumerator<TSecond> e2 = second.GetEnumerator()) {
while (e1.MoveNext()) {
if (e2.MoveNext()) {
yield return resultSelector(e1.Current, e2.Current);
} else {
yield return resultSelector(e1.Current, default(TSecond));
}
}
while (e2.MoveNext()) {
yield return resultSelector(default(TFirst), e2.Current);
}
}
}
}
class Error {
public static Exception ArgumentNull(string parameter) {
return new ArgumentNullException(parameter);
}
}
}
这将允许您构造所需的对象模型,然后将其写入CSV编写器
using (var writer = new StreamWriter(@"C:\test.csv")) {
var records = column1data.ZipOrDefault(column2data,
(Column1, Column2) => new { Column1, Column2 });
var csv = new CsvWriter(writer);
csv.WriteRecords(records);
writer.Flush();
}
答案 1 :(得分:-1)
尝试newtonsoft json.net
像
一样安装click.secho('Error', fg='red', nl=False) # This will prevent the secho statement from starting a new line
click.echo(': This error is ...xx')
这对我有用:
install-package newtonsoft.json