c# - 使用 Newtownsoft,我如何序列化没有属性名称的对象?
问题描述
我正在向客户发送 100 万个FOO
json 列表。
public class FOO
{
public string Foo, Name, Call, Loc, ID;
public double Long, Lat;
public string[] Adr, OpenningHours;
}
但是客户要求我提供特定的输出,因为它会减少数据大小:
删除属性名称,加入地址,然后扁平化列出它们将始终是一周中的 7 天。像:
[
[
"ag",
99.0000000,
9.0000000,
"FOO-FOO BAR",
"ADR1|ADR2|ADR3|ADR4",
"0101",
"07:30-12:00,12:00-19:30",
"07:30-12:00,12:00-19:30",
"07:30-12:00,12:00-19:30",
"07:30-12:00,12:00-19:30",
"07:30-12:00,12:00-19:30",
"07:30-13:00,",
",",
"07H30",
"FOO BAR"
],
]
我对 Address join 或 flatern OpenningHours 没有任何问题。使用:
public class ItemMapper
{
public string Foo, Name, Adr, ID, Call, Loc,
w1, w2, w3, w4, w5, w6, w7;
public double Long, Lat;
}
return
new ItemMapper
{
Foo = this.Foo,
// [...]
Adr = string.Join("|", this.Adr),
w1 = this.OpenningHours[0],
// [...]
w7= this.OpenningHours[6]
};
如果没有纯字符串操作替换等,是否有适当的方法来做到这一点?
List 的序列化会产生不好的结果,我使用编译的 regex remplace 进行修复:
[
{ <-- Not a []
"PopertyName":"PropertyValue", <-- Poperty Name, and :
// ..
"PopertyName":"PropertyValue",
},
]
解决方案
我不推荐它,因为它为您提供了动态 JSON(即您不能从中创建类),但您可以使用 aList<List<string>>
来解决该要求。
给定List<ItemMapper> data
,使用:
var result = data
.Select(item => new List<string>
{
x.Foo,
x.Name,
x.Call,
... // not sure about the order though
})
.ToList();
推荐阅读
- azure - 使用 REST API 下载 Azure Devops Repository 的存档
- vba - IE 自动化 - VBA 错误 - 运行时错误 70:权限被拒绝
- wordpress - Wordpress 站点多次接收来自同一 IP 的请求
- java - 如何在 HashMap 中保留重复项
- angular - 如何解决我的分页错误指示“它在类型上不存在”?
- docker - curl 在脚本内运行时失败
- python - SQLAlchemy 表使用两个外键定义关系
- php - 如何使用日期函数修复 PHP 时区问题
- javascript - jQuery在提交时将输入值分配给隐藏字段
- reactjs - redux-saga api 调用响应过滤