简体   繁体   English

无法反序列化 C# 中的当前 JSON

[英]Cannot deserialize the current JSON in C#

I faced the problem: Cannot deserialize the current JSON object.我遇到了问题:无法反序列化当前的 JSON object。

As follows:如下:

public List<Track> Tracks { get; set; }

public async Task<List<Track>> GetTracking()
{

    using (var httpClient = new HttpClient())
    {
        using (var requests = new HttpRequestMessage(new HttpMethod("GET"), "urlxxxxxxxx..."))
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            requests.Headers.TryAddWithoutValidation("accept", "application/json");

            var response = await httpClient.SendAsync(requests);

            using (HttpContent content = response.Content)
            {
                var jsonStr = content.ReadAsStringAsync().GetAwaiter().GetResult();
                var res = JsonConvert.DeserializeObject<List<Track>>(jsonStr); //Get Error**
                Tracks = res;
            }
        }
    }

    return Tracks;
}

Model Class Model Class

public class Track
{
    public List<Events> events { get; set; }
}

public class Events
{
    public string eventID { get; set; }
    public string eventType { get; set; }
    public string eventDateTime { get; set; }
    public string eventCreatedDateTime { get; set; }
    public string eventClassifierCode { get; set; }
    public string transportEventTypeCode { get; set; }
    public string documentID { get; set; }
    public string shipmentEventTypeCode { get; set; }
    public List<DocumentReferences> documentReferences { get; set; }
    public TransportCall transportCall { get; set; }
}
public class DocumentReferencesMearsk
{
    public string documentReferenceType { get; set; }
    public string documentReferenceValue { get; set; }
}
public class TransportCallMaersk
{
    public string transportCallID { get; set; }
    public string carrierServiceCode { get; set; }
    public string exportVoyageNumber { get; set; }
    public string importVoyageNumber { get; set; }
    public int transportCallSequenceNumber { get; set; }
    public string UNLocationCode { get; set; }
    public string facilityCode { get; set; }
    public string facilityCodeListProvider { get; set; }
    public string facilityTypeCode { get; set; }
    public string otherFacility { get; set; }
    public string modeOfTransport { get; set; }
    public LocationMearsk location { get; set; }
    public VesselMearsk vessel { get; set; }
}

My input data:我的输入数据:

https://drive.google.com/file/d/12g0nHkHlmbU4Af8crHlzKXD_ERIZdCyH/view?usp=sharing https://drive.google.com/file/d/12g0nHkHlmbU4Af8crHlzKXD_ERIZdCyH/view?usp=sharing

在此处输入图像描述

As in my description.正如我的描述。 I get the error: I get the error: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[XX. I get the error: I get the error: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[XX. Models.Track]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. Models.Track]' 因为该类型需要 JSON 数组(例如 [1,2,3])才能正确反序列化。

Even though I declared: public List events { get;即使我声明: public List events { get; set;放; } }

Is the problem I have misunderstood the format of DeserializeObject.是我误解了DeserializeObject的格式的问题。 Looking forward to everyone's help.期待大家的帮助。 Thank感谢

you have an object, not an array你有一个 object,而不是一个数组

var res = JsonConvert.DeserializeObject<Track>(jsonStr);

and fix class并修复 class

public class Events
{
    ....
    public List<DocumentReferencesMearsk> documentReferences { get; set; }
    public TransportCallMaersk transportCall { get; set; }
}

Your model is incomplete and has typos.您的 model 不完整且有拼写错误。 Assuming you have the correct versions of them.假设您拥有它们的正确版本。 You are doing:你正在做:

var res = JsonConvert.DeserializeObject<List<Track>>(jsonStr); 

which should be just:这应该只是:

var res = JsonConvert.DeserializeObject<Track>(jsonStr); 

Your json doesn't have an array at the root level.您的 json 在根级别没有数组。

Full working sample:完整的工作样本:

void Main()
{
    var res = JsonConvert.DeserializeObject<Track>(myJson);
}

public class Track
{
    public List<Events> events { get; set; }
}

public class Events
{
    public string eventID { get; set; }
    public string eventType { get; set; }
    public string eventDateTime { get; set; }
    public string eventCreatedDateTime { get; set; }
    public string eventClassifierCode { get; set; }
    public string transportEventTypeCode { get; set; }
    public string documentID { get; set; }
    public string shipmentEventTypeCode { get; set; }
    public List<DocumentReferencesMearsk> documentReferences { get; set; }
    public TransportCallMaersk transportCall { get; set; }
}
public class DocumentReferencesMearsk
{
    public string documentReferenceType { get; set; }
    public string documentReferenceValue { get; set; }
}
public class TransportCallMaersk
{
    public string transportCallID { get; set; }
    public string carrierServiceCode { get; set; }
    public string exportVoyageNumber { get; set; }
    public string importVoyageNumber { get; set; }
    public int transportCallSequenceNumber { get; set; }
    public string UNLocationCode { get; set; }
    public string facilityCode { get; set; }
    public string facilityCodeListProvider { get; set; }
    public string facilityTypeCode { get; set; }
    public string otherFacility { get; set; }
    public string modeOfTransport { get; set; }
    public Location location { get; set; }
    public Vessel vessel { get; set; }
}
public partial class Location
{
    public string LocationName { get; set; }
    public string Latitude { get; set; }
    public string Longitude { get; set; }
    public string UnLocationCode { get; set; }
    public string FacilityCode { get; set; }
    public string FacilityCodeListProvider { get; set; }
}

public partial class Vessel
{
    public long VesselImoNumber { get; set; }
    public string VesselName { get; set; }
    public string VesselFlag { get; set; }
    public string VesselCallSignNumber { get; set; }
    public string VesselOperatorCarrierCode { get; set; }
    public string VesselOperatorCarrierCodeListProvider { get; set; }
}


static readonly string myJson = @"{
  ""events"": [
    {
      ""eventID"": ""6832920321"",
      ""eventType"": ""SHIPMENT"",
      ""eventDateTime"": ""2019-11-12T07:41:00+08:00"",
      ""eventCreatedDateTime"": ""2021-01-09T14:12:56Z"",
      ""eventClassifierCode"": ""ACT"",
      ""shipmentEventTypeCode"": ""DRFT"",
      ""documentTypeCode"": ""SHI"",
      ""documentID"": ""205284917""
    },
    {
      ""eventID"": ""6832920321"",
      ""eventType"": ""TRANSPORT"",
      ""eventDateTime"": ""2019-11-12T07:41:00+08:00"",
      ""eventCreatedDateTime"": ""2021-01-09T14:12:56Z"",
      ""eventClassifierCode"": ""ACT"",
      ""transportEventTypeCode"": ""ARRI"",
      ""documentReferences"": [
        {
          ""documentReferenceType"": ""BKG"",
          ""documentReferenceValue"": ""ABC123123123""
        },
        {
          ""documentReferenceType"": ""TRD"",
          ""documentReferenceValue"": ""85943567-eedb-98d3-f4ed-aed697474ed4""
        }
      ],
      ""transportCall"": {
        ""transportCallID"": ""123e4567-e89b-12d3-a456-426614174000"",
        ""carrierServiceCode"": ""FE1"",
        ""exportVoyageNumber"": ""2103S"",
        ""importVoyageNumber"": ""2103N"",
        ""transportCallSequenceNumber"": 2,
        ""UNLocationCode"": ""USNYC"",
        ""facilityCode"": ""ADT"",
        ""facilityCodeListProvider"": ""SMDG"",
        ""facilityTypeCode"": ""POTE"",
        ""otherFacility"": ""Balboa Port Terminal, Avenida Balboa Panama"",
        ""modeOfTransport"": ""VESSEL"",
        ""location"": {
          ""locationName"": ""Eiffel Tower"",
          ""latitude"": ""48.8585500"",
          ""longitude"": ""2.294492036"",
          ""UNLocationCode"": ""USNYC"",
          ""facilityCode"": ""ADT"",
          ""facilityCodeListProvider"": ""SMDG""
        },
        ""vessel"": {
          ""vesselIMONumber"": 1801323,
          ""vesselName"": ""King of the Seas"",
          ""vesselFlag"": ""DE"",
          ""vesselCallSignNumber"": ""NCVV"",
          ""vesselOperatorCarrierCode"": ""MAEU"",
          ""vesselOperatorCarrierCodeListProvider"": ""NMFTA""
        }
      }
    }
  ]
}";

EDIT: Result is something like:编辑:结果类似于:

结果样本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM