首页 > 解决方案 > 如何拆分包含 JSON 的 txt 文件?

问题描述

更新

我创建了我的自定义类,现在我可以访问数据了。

该类如下所示:

Public Class GeneralList

    <JsonProperty("Key1")>
    Public Property Key1 As String()

    <JsonProperty("Cola")>
    Public Property Cola As String()

    <JsonProperty("Key2")>
    Public Property Key2 As String()

    <JsonProperty("Key3")>
    Public Property Key3 As String()

    <JsonProperty("Key4")>
    Public Property Key4 As String()

    <JsonProperty("Key5")>
    Public Property Key5 As String()

    <JsonProperty("Key6")>
    Public Property Key6 As String()
End Class

Public Class GeneralListRoot

    <JsonProperty("GeneralList")>
    Public Property  As GeneralList()
End Class

现在我需要做的是,让每个项目都有自己的 txt 文件。我猜我必须重新序列化每个对象并将其写入 txt 文件,但我该怎么做呢?类似于以下内容:

Private Sub splitTXT()

    Dim ReceiptsToProcess As GeneralListRoot = JsonConvert.DeserializeObject(Of GeneralListRoot)(json)

    For i As Integer = 0 To ReceiptsToProcess.GeneralList.Length
        
        Dim str as String = JsonConvert.SerializeObject(New With {Key .data = ReceiptsToProcess.GeneralList(i)})

        'Streamwriter etc etc 
    Next

End Sub

原帖

我有一个非常长的 .txt 文件,其中包含 JSON。

该文件代表了许多收据,其结构如下,每个Key1到Key6都是一个收据:

{
    "GeneralList": [
        {
            "Key1": [
                "Company Name         NIT 1028367023",
                "Sucursal 02                                                        Fact:  68831",
                "Calle Bolivar Nro 156 Telf.:3360000 Santa Cruz-Bolivia   Nov/2020  Nro.Auto:416801000297136",
                "                        F A C T U R A                    Distr.",
                "Actividad Economica: Telecomunicaciones",
                "CI: 1516188 Telefono: 33432352                                     Cajero: 90812",
                "Nombre   : GUILLERMO ANTONIO PARADA SUAREZ                         Fecha :11-02-2021",
                "Contrato : 40000479                                                Hora  :10:02:00",
                "Direccion: CALL SIN_NOMBRE 0081                                    Lugar :Bank",
                "Ref.Pago : 33432352",
                "Fecha de Emision         Fecha Maxima de Entrega  Fecha de Vencimiento",
                "30-11-2020                 03-12-2020              03-01-2021",
                "SERVICIO: TELEFONICO               Categoria: SOCIO    Periodo : 01-11-20 al 30-11-20",
                " "
            ],
            "Cola": [
                "Fecha Pago                    ",
                "11-02-21                      ",
                "Factura                       ",
                "68831                         ",
                "Telefono                      ",
                "33432352                      ",
                "Monto                         ",
                "   150.12                     ",
                "Entidad                       ",
                "40                            ",
                "Cajero                        ",
                " 90812                        ",
                "Hora                          ",
                "10:02:00                      "
            ],
            "Key2": [
                "                                    DETALLE                      IMPORTE Bs.",
                "TARIFA BASICA SOCIO                                                               52.72",
                "REINSTALACION                                                                     27.00",
                "TASA DE REGULACION AFCOOP                                                          0.50",
                "LLAMADA EN ESPERA                                                                  0.00",
                "TELE-CONDOMINIO                                                                   34.40",
                "BLOQUEO CONTROLADO DE LLAMADAS                                                    22.30",
                "IDENTIFICADOR DE LLAMADAS                                                         13.20",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " "
            ],
            "Key3": [
                "Codigo de Control:       17-9B-69-4B-8C           Total Bs.                      150.12",
                "Fecha Limite de Emision: 02-12-2020               Base para credito fiscal:      149.62"
            ],
            "Key4": [
                "Son: Ciento Cincuenta CON 12/100 Bolivianos",
                " ",
                "Mensaje: Estimado Sr.Abonado: Solicitando,en nuestras oficinas su PIN,Ud.puede contar con su detalle de llamadas en forma rapida y comoda a traves de nuestra pag.Web Cotas.com"
            ],
            "Key5": [
                "1028367023|68831|416801000297136|30/11/2020|150.12|149.62|17-9B-69-4B-8C|1516188|0.00|0.00|0.50|0.00"
            ],
            "Key6": [
                "                        ",
                "                        ",
                "                        ",
                "                        ",
                "                        "
            ]
        },
        {
            "Key1": [
                "Company Name         NIT 1028367023",
                "Sucursal 02                                                        Fact:  95423",
                "Calle Bolivar Nro 156 Telf.:3360000 Santa Cruz-Bolivia   Ene/2021  Nro.Auto:416801100312955",
                "                        F A C T U R A                    Distr.0000",
                "Actividad Economica: Telecomunicaciones",
                "CI: 2815655 Telefono: 39219275                                     Cajero: 90812",
                "Nombre   : ANA MARIA SUAREZ DE CUELLAR                             Fecha :11-02-2021",
                "Contrato : 95421287                                                Hora  :10:45:49",
                "Direccion: CALLE RECAREDO RODA 0000                                Lugar :Bank",
                "Ref.Pago : 39219275",
                "Fecha de Emision         Fecha Maxima de Entrega  Fecha de Vencimiento",
                "31-01-2021                 03-02-2021              06-03-2021",
                "SERVICIO: TELEFONICO               Categoria: USUARIO  Periodo : 01-01-21 al 31-01-21",
                " "
            ],
            "Cola": [
                "Fecha Pago                    ",
                "11-02-21                      ",
                "Factura                       ",
                "95423                         ",
                "Telefono                      ",
                "39219275                      ",
                "Monto                         ",
                "   209.00                     ",
                "Entidad                       ",
                "40                            ",
                "Cajero                        ",
                " 90812                        ",
                "Hora                          ",
                "10:45:49                      "
            ],
            "Key2": [
                "                                    DETALLE                      IMPORTE Bs.",
                "PLAN COMBAZO ESENCIAL POSTPAGO                                                   209.00",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " "
            ],
            "Key3": [
                "Codigo de Control:       BB-D6-2A-7C              Total Bs.                      209.00",
                "Fecha Limite de Emision: 12-02-2021               Base para credito fiscal:      209.00"
            ],
            "Key4": [
                "Son: Doscientos Nueve CON 00/100 Bolivianos",
                " ",
                "Mensaje: Estimado Sr.Abonado: Solicitando,en nuestras oficinas su PIN,Ud.puede contar con su detalle de llamadas en forma rapida y comoda a traves de nuestra pag.Web Cotas.com"
            ],
            "Key5": [
                "1028367023|95423|416801100312955|31/01/2021|209.00|209.00|BB-D6-2A-7C|2815655|0.00|0.00|0.00|0.00"
            ],
            "Key6": [
                "                        ",
                "                        ",
                "                        ",
                "                        ",
                "                        "
            ]
        },
        {
            "Key1": [
                "Company Name         NIT 1028367023",
                "Sucursal 02                                                        Fact:  36582",
                "Calle Bolivar Nro 156 Telf.:3360000 Santa Cruz-Bolivia   Dic/2020  Nro.Auto:416801000306848",
                "                        F A C T U R A                    Distr.0049",
                "Actividad Economica: Telecomunicaciones",
                "CI : 1540044 Telefono: 33488769                                    Cajero: 90812",
                "Nombre   : BLANCA ELVIRA MELGAR GOMEZ                              Fecha :11-02-2021",
                "Contrato : 60071759                                                Hora  :13:54:32",
                "Direccion: CALL UV-71  J 0000                                      Lugar :Bank",
                "Ref.Pago : 33488769",
                "Fecha de Emision         Fecha Maxima de Entrega  Fecha de Vencimiento",
                "31-12-2020                 03-01-2021              03-02-2021",
                "SERVICIO: TELEFONICO               Categoria: SOCIO    Periodo : 01-12-20 al 31-12-20",
                " "
            ],
            "Cola": [
                "Fecha Pago                    ",
                "11-02-21                      ",
                "Factura                       ",
                "36582                         ",
                "Telefono                      ",
                "33488769                      ",
                "Monto                         ",
                "   451.80                     ",
                "Entidad                       ",
                "40                            ",
                "Cajero                        ",
                " 90812                        ",
                "Hora                          ",
                "13:54:32                      "
            ],
            "Key2": [
                "                                    DETALLE                      IMPORTE Bs.",
                "PLAN COMBAZO HD AVANZADO PLUS POSTP                                              429.00",
                "TASA DE REGULACION AFCOOP                                                          0.50",
                "BLOQUEO CONTROLADO DE LLAMADAS                                                    22.30",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " ",
                " "
            ],
            "Key3": [
                "Codigo de Control:       D4-3D-C0-83-34           Total Bs.                      451.80",
                "Fecha Limite de Emision: 13-01-2021               Base para credito fiscal:      451.30"
            ],
            "Key4": [
                "Son: Cuatrocientos Cincuenta Y Uno CON 80/100 Bolivianos",
                " ",
                "Mensaje: Estimado Sr.Abonado: Solicitando,en nuestras oficinas su PIN,Ud.puede contar con su detalle de llamadas en forma rapida y comoda a traves de nuestra pag.Web Cotas.com"
            ],
            "Key5": [
                "1028367023|36582|416801000306848|31/12/2020|451.80|451.30|D4-3D-C0-83-34|1540044|0.00|0.00|0.50|0.00"
            ],
            "Key6": [
                "                        ",
                "                        ",
                "                        ",
                "                        ",
                "                        "
            ]
        }
    ]
}

我想将文件拆分为有效的 json 格式。

我需要每个文件(在此示例中总共 3 个)包含每个 Key1 到 Key6 之间的所有信息。文件拆分必须以编程方式完成,因为用户必须能够从服务器保存此文件并将其发送到打印后台处理程序服务。

文件可以是 .txt .json 或 .web

这是一个 vb.net 网络应用程序。我需要在数据网格中显示每个文件的信息,稍后我会弄清楚。

如何拆分文件?

标签: jsonvb.nettext-parsing

解决方案


NewtonSoftJsonConvert.DeserializeObject将满足您的需求。

第一步

按照@Jimi 所说的来创建您的课程。对于下面的示例,我假设生成的类称为PendingReceipts.

第二步

Imports Newtonsoft.Json

第三步

这是一个模拟示例。您必须根据自己的类等对其进行调整。这一行代码神奇地获取了所有 JSON 并用所有数据填充您的类实例属性。

Dim ReceiptsToProcess As PendingReceipts = JsonConvert.DeserializeObject(Of PendingReceipts)(ReceiptJSONcode)

在哪里:

ReceiptsToProcessis 将是类类型的一个新实例,它将包含您需要处理的数据。

PendingReceipts是类类型。

ReceiptJSONcode是一个字符串变量,包含需要处理的 JSON 代码。

第四步

遍历 中的结果数据ReceiptsToProcess。您需要查看课程以了解数据的结构方式,因此您知道获取数据的正确方法。

在这种特殊情况下,按照 JSON 的结构方式,您可以在结果数据的数组中获取数组。我的意思是,对于每个 Key1,匹配的数据表明它是一个数组 - 即每个 Key1 可以有多个值,因此转换器将它创建为一个数组。但是,在您的所有示例中,只给出了一个值。因此,在尝试为其编码之前,您需要了解您的潜在数据。前任。如果您实际上为 Key1 获得了多个值怎么办?还是为 Key2 而不是 Key3?你看懂数据了吗?

了解一下并发布您的代码。如果需要,我会进一步提供帮助。

更新

你现在已经得到了 90%。如果您只想提取每个内容并单独重新保存,这比您的帖子更容易。在这里,您可以看到一点点查看数据,以及如何导出每个数据。

Dim res As String = ""
Dim myjson As String = TextBox1.Text
Dim ReceiptstoProcess As PendingReceipts = JsonConvert.DeserializeObject(Of PendingReceipts)(myjson)
res += $"Count: {ReceiptstoProcess.GeneralList.Count}" + vbCrLf

If ReceiptstoProcess.GeneralList.Count > 0 Then

    'We can look at individual data points:
    For i = 0 To ReceiptstoProcess.GeneralList.Count - 1
        res += vbCrLf + $"RECEIPT #{i}-------------------------" + vbCrLf
        'NOTE: You could multiple values for Key3 etc.  You might need to iterate through them.  This doesn't go to that level, but it would be simple.
        res += "Key 3:" + vbCrLf + ReceiptstoProcess.GeneralList(i).Key3(0).ToString + vbCrLf
        res += "Key 5:" + vbCrLf + ReceiptstoProcess.GeneralList(i).Key5(0).ToString + vbCrLf
    Next
    res += vbCrLf

    res += "----------------" + vbCrLf + vbCrLf

    'We can serialize each receipt separately from the rest, and then do something with it:
    For i = 0 To ReceiptstoProcess.GeneralList.Count - 1
        res += vbCrLf + $"RECEIPT #{i}-------------------------" + vbCrLf
        res += JsonConvert.SerializeObject(ReceiptstoProcess.GeneralList(i)) + vbCrLf + vbCrLf
    Next
    res += vbCrLf

Else
    res += "No receipts to process"
End If
MsgBox(res)

最大的不同是你有:

Dim str as String = JsonConvert.SerializeObject(New With {Key .data = ReceiptsToProcess.GeneralList(i)})

但这对我有用:

Dim str as String = JsonConvert.SerializeObject(ReceiptstoProcess.GeneralList(i))

PS我实际上并没有尝试你写的东西,所以也许它会起作用。我的第一反应就是看起来像是一些不必要的额外代码。


推荐阅读