C 语言中的序列化和反序列化 HttpClient 有效负载#

Serialization and Deserialization HttpClient payload in C#

提问人:GIovanni 提问时间:11/14/2023 最后编辑:GIovanni 更新时间:11/14/2023 访问量:64

问:

我必须使用 System.Net.Http.HttpClient 从 API 中检索一些详细的 json 数据。为了以所需的格式正确地反序列化这些数据,我必须删除属性名称(而不是值)中的空格和特殊字符(例如重音和下划线),然后删除 desiderd 格式中不存在的“属性名称”:“属性值”对。我怎样才能做到这一点?

我尝试过这样的东西,但没有奏效:

                string apiResponse = await response.Content.ReadAsStringAsync();
                var jsonSerializerSettings = new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
                var interimObject = JsonConvert.DeserializeObject<ExpandoObject>(apiResponse);
                var myJsonOutput = JsonConvert.SerializeObject(interimObject,  jsonSerializerSettings);
                var responseData = JsonConvert.DeserializeObject<APILindeResponseWrapper<PatientData>>(myJsonOutput);

特别是,消除了空格。 我的APILindeResponseWrapper是:

{
    public class APILindeResponseWrapper<T>
    {
        public string Status { get; set; }
        public List<DataWrapper<T>> Data { get; set; }
        public string Message;

    }

    public partial class DataWrapper<T>
    {
        public Timestamp Timestamp { get; set; }
        public T Data;
        
    }
    public partial class Timestamp
    {
        public string Type;
        public string[] Data;

    }
}

我的病人数据是:

    public class PatientData
    {
        public PatientData() { }
       
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public string? No { get; set; }
        
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public string? Nome { get; set; }
        
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public string? FirstName { get; set; }
        
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public string? Surname { get; set; }  
        public string? CittaNascita { get; set; }
        
        public DateTime? DataDiNascita { get; set; }
        
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public int? Sesso { get; set; }   
        public string? CodiceFiscale { get; set; }
       
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public string? Indirizzo { get; set; }   
        public string? Frazione { get; set; }
        
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public string? CAP { get; set; }
        
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public string? Città { get; set; }
        
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public string? Provincia { get; set; }   
        public string? TelefonoDiConsegna { get; set; }
        public string? IndirizzoResidenza { get; set; }
        public string? CAPResidenza { get; set; }
        public string? CittaResidenza { get; set; }
        public string? ProvinciaResidenza { get; set; }
       
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public string? ShortDim5 { get; set; }
        public DateTime? DataAutorizzazione { get; set; }
        
        public DateTime? DataScadenza { get; set; }
       
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public string? CustomerNo { get; set; }
        
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public string? ShortDim4 { get; set; }
              
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public string? StatoDelServizio { get; set; }
        
        [Required(ErrorMessage = "{0} Must Be Filled")]
        public string? ContractNo { get; set; }
        public DateTime? DataDiInstallazione { get; set; }
        
        public string?  Medico { get; set; }
       
    }   


邮递员的 API 响应示例如下:

{
    "status": 200,
    "data": [
        {
            "timestamp": {
                "type": "Buffer",
                "data": [
                    0,
                    0,
                    0,
                    1,
                    179,
                    245,
                    49,
                    202
                ]
            },
            "Customer No_": "M037984",
            "Name": "ASST PAVIA",
            "No_": "P260339",
            "Codice Ricerca": "COMASCHI ROMOLO 19300523",
            "Nome": "COMASCHI ROMOLO",
            "Nome2": "",
            "Data di Nascita": "1930-05-23T00:00:00.000Z",
            "Luogo di Nascita": "",
            "Sesso": 1,
            "Codice Fiscale": "CMSRML30E23M119E",
            "Indirizzo": "CASA TORREGGIANI 8",
            "Città": "MONTECALVO VERSIGGIA",
            "CAP": "27047",
            "Provincia": "PV",
            "Cod_ Regione": "LOM",
            "Codice Paese": "IT",
            "Global Dimension 1 Code": "DOM221000",
            "Global Dimension 2 Code": "DOM202",
            "Contract No_": "CNT037453",
            "Address 2": "",
            "Ultimo Stato": "2019-05-08T00:00:00.000Z",
            "Stato del Servizio": "D",
            "Sospesa Fatturazione": 1,
            "Sospeso Servizio": 1,
            "Gita": "",
            "Giro": 0,
            "A Giro": 0,
            "Cadenza": 0,
            "Tipo Consegna": "",
            "Data Ultimo Aggior_ Consegna": "1753-01-01T00:00:00.000Z",
            "Prossima Consegna Prevista": "1753-01-01T00:00:00.000Z",
            "Time Slot": "",
            "Indirizzo di Consegna": "CASA TORREGGIANI 8",
            "CAP di Consegna": "27047",
            "Comune di Consegna": "MONTECALVO VERSIGGIA",
            "Provincia di Consegna": "PV",
            "Cod_ Regione di Consegna": "LOM",
            "Telefono di Consegna": "3403604306",
            "Piano": "",
            "NrInterno": "",
            "Ascensore": 0,
            "Data Ultima Modifica": "2019-05-09T00:00:00.000Z",
            "Flusso Prescritto": 0,
            "Oredie": 0,
            "Flusso Reale": 0,
            "Tipo di Fornitura": 0,
            "Prodotto": "",
            "Apparecchiatura": "",
            "Posizione Sanitaria": "",
            "Somministrazione": "",
            "Data di Installazione": "2019-04-17T00:00:00.000Z",
            "Data di Ritiro": "1753-01-01T00:00:00.000Z",
            "Data Ultima Consegna": "1753-01-01T00:00:00.000Z",
            "Medico": "SPRT",
            "ASL": "",
            "Distretto": "",
            "Data Autorizzazione": "1753-01-01T00:00:00.000Z",
            "Data Scadenza": "1753-01-01T00:00:00.000Z",
            "Protocollo": "",
            "Autorizzazione": "",
            "Ricetta": "",
            "Altro": "",
            "Numerazione": "",
            "Bloccato": 0,
            "ID_Utente": "LINDE\\IT00F4",
            "Flusso Strumenti": 0,
            "Flusso Ossigeno": 0,
            "Parente stretto": "",
            "MedicoImport": "",
            "ProdottoImport": "",
            "Diagnosi": "",
            "SospesoImport": "",
            "StrumentoImport": "",
            "DescrStrumento": "",
            "FRI": 0,
            "ORI": 0,
            "Informazioni Ambientali": "",
            "Unità Operativa": "",
            "Flusso Accessori": 0,
            "ASLN": "",
            "DistrettoN": "",
            "Totale Sospeso": 0,
            "Tot Sospeso FT": 0,
            "Dotazione": 0,
            "Usa Consumo Reale": 0,
            "Conta": 0,
            "Nr_ Farmacia": "",
            "Tipo Ventilazione": 0,
            "Tipo di Servizio": 0,
            "Tipologia": 1,
            "Erma": 0,
            "Ult_ Cons_ POT": "1753-01-01T00:00:00.000Z",
            "Note Palmare": "",
            "Provenienza": "",
            "ShortDim3": "ASL",
            "ShortDim4": "020400",
            "ShortDim5": "GOX",
            "ShortDim6": "010909000",
            "ShortDim9": "",
            "ShortDim10": "P260339",
            "Shortdim12": "CA",
            "Frazione": "",
            "Zona": "",
            "Venditore": "",
            "Filiale": "",
            "Agente": "",
            "ASLOLD": "",
            "DistrettoOLD": "",
            "SomministrazioneOld": "",
            "MedicoOLD": "",
            "CatPAZOLD": "",
            "StrumentoOLD": "",
            "Sync Date Modified": "2019-05-09T09:21:44.473Z",
            "First Name": "ROMOLO",
            "Middle Name": "",
            "Surname": "COMASCHI",
            "Initials": "",
            "Installation Module": 0,
            "ASL Code": "",
            "Città Nascita": "",
            "CAP Nascita": "",
            "E-mail": "",
            "Data ultima assistenza": "1753-01-01T00:00:00.000Z",
            "Patient Type": 1,
            "STP Code": "",
            "CAP Iscr_ Sanitaria": "",
            "City Iscr_ Sanitaria": "",
            "Indirizzo Residenza": "CASA TORREGGIANI 8",
            "Città Residenza": "MONTECALVO VERSIGGIA",
            "CAP Residenza": "27047",
            "Provincia Residenza": "PV",
            "Cod_ Regione Residenza": "LOM",
            "Codice Paese Residenza": "IT",
            "Standard Next Deliv_ Date": 0,
            "User Filter Dim_ 1": "DOM221000",
            "Patient Id": "",
            "Patient Profile Code": "",
            "Istat Code": "018096",
            "Patologia": "",
            "RecID": {
                "type": "Buffer",
                "data": [
                    96,
                    234,
                    0,
                    0,
                    2,
                    123,
                    255,
                    80,
                    0,
                    50,
                    0,
                    54,
                    0,
                    48,
                    0,
                    51,
                    0,
                    51,
                    0,
                    57,
                    0,
                    0,
                    0,
                    0,
                    0
                ]
            },
            "Range Of Supports Code": "",
            "Service Starting Date": "1753-01-01T00:00:00.000Z",
            "Service Expiration Date": "1753-01-01T00:00:00.000Z",
            "Service Item No_": "",
            "Service Order No_": "",
            "RecGUID": "197FA2DE-7410-45CF-B36B-53E808D37497",
            "Delivery Type": ""
        },
        {
            "timestamp": {
                "type": "Buffer",
                "data": [
                    0,
                    0,
                    0,
                    1,
                    180,
                    115,
                    47,
                    230
                ]
            },
            "Customer No_": "M037984",
            "Name": "ASST PAVIA",
            "No_": "P260347",
            "Codice Ricerca": "MERALDI LUIGI 19310523",
            "Nome": "MERALDI LUIGI",
            "Nome2": "",
            "Data di Nascita": "1931-05-23T00:00:00.000Z",
            "Luogo di Nascita": "",
            "Sesso": 1,
            "Codice Fiscale": "MRLLGU31E23I968J",
            "Indirizzo": "VIA CARDUCCI 16C",
            "Città": "PORTALBERA",
            "CAP": "27040",
            "Provincia": "PV",
            "Cod_ Regione": "LOM",
            "Codice Paese": "IT",
            "Global Dimension 1 Code": "DOM221000",
            "Global Dimension 2 Code": "DOM202",
            "Contract No_": "CNT037453",
            "Address 2": "",
            "Ultimo Stato": "2019-05-13T00:00:00.000Z",
            "Stato del Servizio": "SOS",
            "Sospesa Fatturazione": 1,
            "Sospeso Servizio": 1,
            "Gita": "",
            "Giro": 0,
            "A Giro": 0,
            "Cadenza": 0,
            "Tipo Consegna": "",
            "Data Ultimo Aggior_ Consegna": "1753-01-01T00:00:00.000Z",
            "Prossima Consegna Prevista": "1753-01-01T00:00:00.000Z",
            "Time Slot": "",
            "Indirizzo di Consegna": "VIA CARDUCCI 16C",
            "CAP di Consegna": "27040",
            "Comune di Consegna": "PORTALBERA",
            "Provincia di Consegna": "PV",
            "Cod_ Regione di Consegna": "LOM",
            "Telefono di Consegna": "3351028031",
            "Piano": "",
            "NrInterno": "",
            "Ascensore": 0,
            "Data Ultima Modifica": "2019-05-08T00:00:00.000Z",
            "Flusso Prescritto": 0,
            "Oredie": 0,
            "Flusso Reale": 0,
            "Tipo di Fornitura": 0,
            "Prodotto": "",
            "Apparecchiatura": "",
            "Posizione Sanitaria": "",
            "Somministrazione": "",
            "Data di Installazione": "2019-05-13T00:00:00.000Z",
            "Data di Ritiro": "1753-01-01T00:00:00.000Z",
            "Data Ultima Consegna": "1753-01-01T00:00:00.000Z",
            "Medico": "SPRT",
            "ASL": "",
            "Distretto": "",
            "Data Autorizzazione": "1753-01-01T00:00:00.000Z",
            "Data Scadenza": "1753-01-01T00:00:00.000Z",
            "Protocollo": "",
            "Autorizzazione": "",
            "Ricetta": "",
            "Altro": "",
            "Numerazione": "",
            "Bloccato": 0,
            "ID_Utente": "LINDE\\IT00F4",
            "Flusso Strumenti": 0,
            "Flusso Ossigeno": 0,
            "Parente stretto": "",
            "MedicoImport": "",
            "ProdottoImport": "",
            "Diagnosi": "",
            "SospesoImport": "",
            "StrumentoImport": "",
            "DescrStrumento": "",
            "FRI": 0,
            "ORI": 0,
            "Informazioni Ambientali": "",
            "Unità Operativa": "",
            "Flusso Accessori": 0,
            "ASLN": "",
            "DistrettoN": "",
            "Totale Sospeso": 0,
            "Tot Sospeso FT": 0,
            "Dotazione": 0,
            "Usa Consumo Reale": 0,
            "Conta": 0,
            "Nr_ Farmacia": "",
            "Tipo Ventilazione": 0,
            "Tipo di Servizio": 0,
            "Tipologia": 1,
            "Erma": 0,
            "Ult_ Cons_ POT": "1753-01-01T00:00:00.000Z",
            "Note Palmare": "",
            "Provenienza": "",
            "ShortDim3": "ASL",
            "ShortDim4": "020400",
            "ShortDim5": "GOX",
            "ShortDim6": "010909000",
            "ShortDim9": "",
            "ShortDim10": "P260347",
            "Shortdim12": "TM",
            "Frazione": "",
            "Zona": "",
            "Venditore": "",
            "Filiale": "",
            "Agente": "",
            "ASLOLD": "",
            "DistrettoOLD": "",
            "SomministrazioneOld": "",
            "MedicoOLD": "",
            "CatPAZOLD": "",
            "StrumentoOLD": "",
            "Sync Date Modified": "2019-05-08T10:52:15.283Z",
            "First Name": "LUIGI",
            "Middle Name": "",
            "Surname": "MERALDI",
            "Initials": "",
            "Installation Module": 0,
            "ASL Code": "",
            "Città Nascita": "",
            "CAP Nascita": "",
            "E-mail": "",
            "Data ultima assistenza": "1753-01-01T00:00:00.000Z",
            "Patient Type": 1,
            "STP Code": "",
            "CAP Iscr_ Sanitaria": "",
            "City Iscr_ Sanitaria": "",
            "Indirizzo Residenza": "VIA CARDUCCI 16C",
            "Città Residenza": "PORTALBERA",
            "CAP Residenza": "27040",
            "Provincia Residenza": "PV",
            "Cod_ Regione Residenza": "LOM",
            "Codice Paese Residenza": "IT",
            "Standard Next Deliv_ Date": 0,
            "User Filter Dim_ 1": "DOM221000",
            "Patient Id": "",
            "Patient Profile Code": "",
            "Istat Code": "018118",
            "Patologia": "",
            "RecID": {
                "type": "Buffer",
                "data": [
                    96,
                    234,
                    0,
                    0,
                    2,
                    123,
                    255,
                    80,
                    0,
                    50,
                    0,
                    54,
                    0,
                    48,
                    0,
                    51,
                    0,
                    52,
                    0,
                    55,
                    0,
                    0,
                    0,
                    0,
                    0
                ]
            },
            "Range Of Supports Code": "",
            "Service Starting Date": "1753-01-01T00:00:00.000Z",
            "Service Expiration Date": "1753-01-01T00:00:00.000Z",
            "Service Item No_": "",
            "Service Order No_": "",
            "RecGUID": "06A7233E-F5E0-4637-8EE9-DB680681EC0A",
            "Delivery Type": ""
        }
    ],
    "message": "data retrieved successfully"
}
C# .NET REST json.net JSON 反序列化

评论

0赞 Morten Bork 11/14/2023
您尝试序列化的模型具有带有重音的属性名称,这是故意的吗?如果是这样,我不确定为什么您需要删除口音等?
0赞 GIovanni 11/14/2023
你是对的。我必须与我的团队领导交谈,以决定应该更改什么要求,是模型上的要求还是关于去除口音的要求。让我们假设模型是错误的,我也必须删除重音。
0赞 GIovanni 11/14/2023
我只是意识到我复制了错误的 API 响应。我已经编辑并更正了错误。这是对 Item API 资源的响应,而不是对患者的响应。我必须工作的另一个 API。当然,问题中的任何变化都会发生变化。

答:

0赞 Morten Bork 11/14/2023 #1

我不知道简单地告诉你这些例子是否适用于任何属性就足够了?

     [JsonProperty("Global Dimension 1 Code")]
    public string GlobalDimension1Code {get;set;}

[JsonProperty("Unità Operativa")]
        public string UnitOperativa { get; set; }

它会将字符串中的“奇数”命名属性映射到模型中的“正确”命名属性。

然后,只需在模型上没有您希望忽略的属性,就会将它们从对象中删除。

我仍然对这里提出的任务感到有些困惑,因为你的措辞有点奇怪?但这应该可以解决你的问题,是吗? 如果没有,请详细说明为什么不这样做。

我没有看到一种情况,在这种情况下,尝试以这种方式更改属性名称是相关的,当您可以将映射作为模型上的属性启用时,是吗?

您甚至只需要执行:

var responseData = JsonConvert.DeserializeObject<APILindeResponseWrapper<PatientData>>(apiResponse);

评论

0赞 GIovanni 11/14/2023
关键是我不能碰我的模型,因为我也使用它们来反序列化来自其他来源 (excel) 的数据,而不仅仅是来自 API。而且我宁愿不要重复,只要源代码更改,我想重用验证代码。因此,我尝试首先修改字符串响应,然后以所需的患者数据格式进行反序列化,但 ContractResolver 不起作用
0赞 Morten Bork 11/14/2023
我有点困惑,如果您希望解析另一种类型的 patientData,让我们将其称为 PatientDataAdvanced,该对象将定义不同的属性(并且可能具有不同的来源)您还必须为 APILindeResponseWrapper 的特定实例定义所述模型<PatientData>>这需要是 APILindeResponseWrapper<PatientDataAdvanced>>...如果我理解正确的话,你实际上不是在回避这个问题,你提出的解决方案?
0赞 Morten Bork 11/14/2023
也许这个答案也可以解决你的问题?stackoverflow.com/questions/43714050/......
0赞 GIovanni 11/14/2023
我正在尝试找到一种方法来修改逆向工程中的响应,而不是复制实现模型的模型。这是因为我想重用验证代码并保留模块化PatientDataPatientDataAdvanced
0赞 GIovanni 11/14/2023
我终于在 stackoverflow.com/questions/43714050/ 中使用了这种方法......