从JsonReader读取JObject时出错。当前的JsonReader项不是对象:StartArray。路径

时间:2016-01-09 06:45:39

标签: c# json.net

我正在处理涉及位置的Windows Phone 8.1应用程序。我从我的API接收Json数据。我的API返回的内容如下:

[{
    "country": "India",
    "city": "Mall Road, Gurgaon",
    "area": "Haryana",
    "PLZ": "122002",
    "street": "",
    "house_no": "",
    "POI": "",
    "type": "17",
    "phone": "",
    "lng": 77.08972334861755,
    "lat": 28.47930118040612,
    "formatted_address": "Mall Road, Gurgaon 122002, Haryana, India"
},
{
    "country": "India",
    "city": "Mall Road, Kanpur",
    "area": "Uttar Pradesh",
    "PLZ": "208004",
    "street": "",
    "house_no": "",
    "POI": "",
    "type": "17",
    "phone": "",
    "lng": 80.35783410072327,
    "lat": 26.46026740300029,
    "formatted_address": "Mall Road, Kanpur 208004, Uttar Pradesh, India"
},
{
    "country": "India",
    "city": "Mall Road Area, Amritsar",
    "area": "Punjab",
    "PLZ": "143001",
    "street": "",
    "house_no": "",
    "POI": "",
    "type": "17",
    "phone": "",
    "lng": 74.87286686897278,
    "lat": 31.64115178002094,
    "formatted_address": "Mall Road Area, Amritsar 143001, Punjab, India"
},
{
    "country": "India",
    "city": "Vasant Kunj (Mall Road Kishan Garh), New Delhi",
    "area": "Delhi",
    "PLZ": "110070",
    "street": "",
    "house_no": "",
    "POI": "",
    "type": "18",
    "phone": "",
    "lng": 77.1434211730957,
    "lat": 28.51363217008815,
    "formatted_address": "Vasant Kunj (Mall Road Kishan Garh), New Delhi 110070, Delhi, India"
}]

我正在反序列化我的Json数据并将其放入名为LocationData的类中。当我运行我的代码时,它给了我一个错误:

  

从JsonReader读取JObject时出错。当前的JsonReader项不是对象:StartArray。路径

我哪里错了?这是我的代码:

private async void GetAPIData()
    {
        string _serviceUrl = "https://api.myweblinkapiprovider/v2&q=" + UserRequestedLocation;
        HttpClient client = new HttpClient();

        HttpResponseMessage responce = await client.GetAsync(new Uri(_serviceUrl));

        if (responce.Content != null)
        {
            var respArray = JObject.Parse(await responce.Content.ReadAsStringAsync());
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            var rcvdData = JsonConvert.DeserializeObject<LocationData>(respArray.ToString(), settings);
            UpdateMapData(rcvdData);
            UpdateTextData(rcvdData);
        }
    }

我也尝试过使用JArray。我的代码如下:

 private async void GetAPIData()
    {
        string _serviceUrl = "https://api.myweblinkprovider.com/v3?fun=geocode&lic_key=MyKey" + UserRequestedLocation;
        HttpClient client = new HttpClient();

        HttpResponseMessage responce = await client.GetAsync(new Uri(_serviceUrl));

        JArray arr = JArray.Parse(await responce.Content.ReadAsStringAsync());

        foreach (JObject obj in arr.Children<JObject>())
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr.ToString(), settings);
            UpdateMapData(rcvdData);
            UpdateTextData(rcvdData);
        }
    }

它也给了我一个错误:

  

无法将当前JSON数组(例如[1,2,3])反序列化为类型'MMI_SpeechRecog.Model.LocationData',因为该类型需要JSON对象(例如{"name":"value"})才能正确反序列化。

3 个答案:

答案 0 :(得分:58)

您的问题的第一部分是Why do I get a JsonReaderException with this code?的副本,但该(我)答案中最相关的部分是:

  

[A] JObject不是JSON.net中所有内容的基本类型,但JToken是。{1}}。所以即使你可以说,

object i = new int[0];
     

在C#中,你不能说,

JObject i = JObject.Parse("[0, 0, 0]");
     

在JSON.net。

您想要的是JArray.Parse,它会接受您传递的数组(在您的API响应中以开头[表示)。这就是&#34; StartArray&#34;在错误消息中告诉你。

至于您使用JArray时发生的情况,您使用arr代替obj

var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);

交换它,我相信它应该有效。

虽然我很想直接将arr反序列化为IEnumerable<LocationData>,这样可以节省一些循环遍历数组的代码和工作量。如果您不打算单独使用已解析的版本,最好避免使用它。

答案 1 :(得分:19)

在这种情况下,您知道在数组的第一个位置有所有项目,您可以将字符串解析为JArray,然后使用JObject.Parse解析第一个项目

var  jsonArrayString = @"
[
  {
    ""country"": ""India"",
    ""city"": ""Mall Road, Gurgaon"",
  },
  {
    ""country"": ""India"",
    ""city"": ""Mall Road, Kanpur"",
  }
]";
JArray jsonArray = JArray.Parse(jsonArrayString);
dynamic data = JObject.Parse(jsonArray[0].ToString());

答案 2 :(得分:5)

我遇到了与我的Xamarin Windows Phone 8.1应用程序非常相似的问题。 JObject.Parse(json)不适合我的原因是因为我的Json有一个开头“[”和一个结尾“]”。为了使它工作,我不得不删除这两个字符。从您的示例来看,您可能会遇到同样的问题。

jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });

然后我能够使用JObject.Parse(jsonResult),一切正常。