首页 > 解决方案 > 使用 Newtownsoft,我如何序列化没有属性名称的对象?

问题描述

我正在向客户发送 100 万个FOOjson 列表。

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",
    },
]

标签: c#json

解决方案


我不推荐它,因为它为您提供了动态 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();

推荐阅读