You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中MarineTraffic API返回JSON无法反序列化问题求助

解决MarineTraffic API反序列化错误的方案

这个错误其实很典型——你把单个JSON对象当成了JSON数组来反序列化,类型完全不匹配。咱们一步步来解决:

1. 先明确API返回的JSON结构

你的测试接口返回的应该是一个顶层对象,而不是数组。根据MarineTraffic的Vessel Master Data API文档,它的结构大概是这样的:

{
  "metadata": {
    "timestamp": "2024-05-20T12:34:56Z",
    "count": 1
    // 其他元数据字段
  },
  "data": [
    {
      "imo": "9661792",
      "name": "YOUR_VESSEL_NAME",
      // 其他船舶主数据字段
    }
  ]
}

注意:metadata是单个对象(用{}包裹),而data才是数组(用[]包裹)。你之前错误地把整个响应反序列化为List<Metadata>,但实际顶层是包含metadata和data的对象。

2. 检查你的C#实体类定义

确保你的MarineApiData(顶层类)正确对应JSON的结构,属性名要和JSON的键一致(或者用特性映射大小写/命名差异)。比如用System.Text.Json的话,正确的类定义应该是这样:

using System.Text.Json.Serialization;

public class MarineApiData
{
    [JsonPropertyName("metadata")]
    public Metadata Metadata { get; set; }

    [JsonPropertyName("data")]
    public List<Datum> Data { get; set; }
}

public class Metadata
{
    [JsonPropertyName("timestamp")]
    public DateTime Timestamp { get; set; }

    [JsonPropertyName("count")]
    public int Count { get; set; }

    // 根据API文档添加其他元数据属性
}

public class Datum
{
    [JsonPropertyName("imo")]
    public string Imo { get; set; }

    [JsonPropertyName("name")]
    public string VesselName { get; set; }

    // 根据API文档添加其他船舶主数据属性
}

如果你用的是Newtonsoft.Json(Json.NET),把JsonPropertyName换成JsonProperty特性即可。

3. 修改反序列化代码

把原来反序列化为List<Metadata>的代码,改成反序列化为MarineApiData类型。比如:

用System.Text.Json的示例:

public async Task<MarineApiData> GetMarineApiData(string apiUrl)
{
    using var httpClient = new HttpClient();
    var jsonResponse = await httpClient.GetStringAsync(apiUrl);
    return JsonSerializer.Deserialize<MarineApiData>(jsonResponse);
}

用Newtonsoft.Json的示例:

public async Task<MarineApiData> GetMarineApiData(string apiUrl)
{
    using var httpClient = new HttpClient();
    var jsonResponse = await httpClient.GetStringAsync(apiUrl);
    return JsonConvert.DeserializeObject<MarineApiData>(jsonResponse);
}

4. 验证和调试小技巧

  • 如果不确定JSON结构,可以先把API返回的字符串打印出来(或者直接用浏览器调用测试接口查看),确认每个字段的名称和层级。
  • 如果遇到属性映射错误,可以添加序列化配置忽略未知字段,避免反序列化失败:
    // System.Text.Json
    var options = new JsonSerializerOptions { IgnoreNullValues = true, IgnoreReadOnlyProperties = true };
    var marineData = JsonSerializer.Deserialize<MarineApiData>(jsonResponse, options);
    

这样修改后,就能正确把API返回的JSON反序列化为对应的C#对象了。

内容的提问来源于stack exchange,提问作者dotnetdevcsharp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:07:30