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

JObject解析含数组的JSON报错,需提取lat与lon字段

问题解决:解析GeoJSON数组提取经纬度字段

待解析JSON内容

[{
  "place_id":84979036,
  "licence":"Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
  "powered_by":"Map Maker: https://maps.co",
  "osm_type":"node",
  "osm_id":8358755414,
  "boundingbox":["35.8497801","35.8897801","-114.6800654","-114.6400654"],
  "lat":"35.8697801",
  "lon":"-114.6600654",
  "display_name":"Willow Beach, Mohave County, Arizona, United States",
  "class":"place",
  "type":"village",
  "importance":0.47500000000000003
}]

报错信息

Newtonsoft.Json.JsonReaderException: 'Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.'

现有代码

bool PullGeoJson(string city, string state, out string[] output)
{
    HttpResponse<string> response = UnirestLocationRequest(city, state);
    Console.WriteLine(response.Body.ToString());
    JObject json = JObject.Parse(response.Body.ToString());
    output = new string[2];
    output[0] = json.GetValue("lat").ToString();
    output[1] = json.GetValue("lon").ToString();
    return !(output == null);
}

错误原因

并非boundingbox数组导致解析错误,实际问题是接口返回的JSON是数组类型(外层包含[]),但代码中用JObject.Parse尝试解析成单个JSON对象,因此触发异常。

修正代码

改用JArray.Parse解析数组,提取第一个元素后再获取lat和lon字段:

bool PullGeoJson(string city, string state, out string[] output)
{
    HttpResponse<string> response = UnirestLocationRequest(city, state);
    Console.WriteLine(response.Body.ToString());
    // 解析为JSON数组
    JArray jsonArray = JArray.Parse(response.Body.ToString());
    output = new string[2];
    // 取数组第一个元素(假设返回结果中第一个对象是目标数据)
    JObject jsonObj = jsonArray[0] as JObject;
    if (jsonObj != null)
    {
        output[0] = jsonObj.GetValue("lat").ToString();
        output[1] = jsonObj.GetValue("lon").ToString();
    }
    return output != null;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:50:21