Newtonsoft json反序列化错误 [英] Newtonsoft json deserialize error

查看:471
本文介绍了Newtonsoft json反序列化错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi,
I am trying to use Newtonsoft JSon to deserialize to my class, but receives an error:
Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll
Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in System.Private.CoreLib.dll







Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'PassatRep.LocIQRoot' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.'







Debug returns the following

[{"place_id":"83003376","licence":"\u00a9 LocationIQ.com CC BY 4.0, Data \u00a9 OpenStreetMap contributors, ODbL 1.0","osm_type":"way","osm_id":"27462943","boundingbox":["55.3283734","55.3284947","8.7620641","8.7623819"],"lat":"55.3283734","lon":"8.7620641","display_name":"Torvet, Ribe, Esbjerg Municipality, Region of Southern Denmark, 6760, Denmark","class":"highway","type":"pedestrian","importance":0.31}]

Here is a link to the website where the Json response is located










What is wrong with the Json response?
Thank you in advance

Here is my class




<pre>Public Class LocationIQ
    Public Shared Async Function GetLocationIQ(ByVal SearchFor As String) As Task(Of LocIQRoot) 
        Debug.WriteLine(Keys.LocationIQKey)
        Dim httpn = New HttpClient()

        Dim url As String = "https://eu1.locationiq.com/v1/search.php?key=" & Keys.LocationIQKey & "&q=" & SearchFor & "&format=json"
        
 Dim response As HttpResponseMessage = Await httpn.GetAsync(url)
        Dim result = Await response.Content.ReadAsStringAsync()

        Debug.WriteLine(result)

        Dim data As LocIQRoot = JsonConvert.DeserializeObject(Of LocIQRoot)(result)
        Return data
    End Function
End Class

Public Class LocIQRoot
    Public Property Loc() As LocIQ
End Class

Public Class LocIQ
    ' https://locationiq.com/docs#forward-geocoding
    Public Property place_id As String
    Public Property licence As String
    Public Property osm_type As String
    Public Property osm_id As String
    Public Property boundingbox As List(Of String)
    Public Property lat As String
    Public Property lon As String
    Public Property display_name As String
    Public Property IQclass As String
    Public Property type As String
    Public Property importance As Double
    Public Property icon As String
End Class

    Private Async Sub btnTest3_Click(sender As Object, e As RoutedEventArgs) Handles btnTest3.Click
        Dim aa As LocIQRoot = Await LocationIQ.GetLocationIQ("Torvet 1 28 ribe")
    End Sub





我的尝试:





What I have tried:

I have tried to fix this error, but I think it has something to with the way this Json response is presented

推荐答案

因为你试图让图书馆做一些不打算做的事;将值从指定类型数组转换为您需要的类型对象是非法且不安全的。



几乎在每种语言中,数组都是同一类型元素的集合。即使在JavaScript领域,您也可以创建一个数组并在容器中放入相同的对象,然后序列化数组,通过网络将其传递给另一台计算机,或者将其留在那里作为未来外星种族的证据,一次要将数据从字符串读取到对象,您需要确保将对象解析为正确的表示形式。在JavaScript中,您可以轻松判断字符串数据是数组还是对象表示,第一个字符是 [表示数组, {表示对象。否则他们大多无效。



但问题来了。您现在尝试读取数组的数据,但您尝试将其解析为对象。您告诉库解析一个对象,并为它提供数组的数据。



要修复它,只需将列表界面作为类型参数传递,也许这样,

Because you are trying to make the library do something that it is not intended to do; it is illegal and not safe to convert the values from the type specified, array, to the type that you require, object.

In almost every language, an array is a collection of elements of the same type. Even in the JavaScript realm, you would create an array and put in the same objects in the container and then you serialize the array, pass it over to another computer over the network, or leave it there as an evidence to future alien race, once the data is to be read from string to an object, you need to make sure you are parsing the object to the correct representation. In JavaScript, you can easily tell whether string data is an array or an object representation, the first character being [ means an array, and { meaning an object. Otherwise they are mostly invalid.

But here comes the problem. You are trying to now read the data that is array, but you are trying to parse it as an object. You are telling the library to parse an object, and are providing it with data that is for an array.

To fix it, just pass the list interface as the type parameter, maybe this,
' I am no VB.NET expert
Dim data As List(Of LocIQRoot) = JsonConvert.DeserializeObject(Of List(Of LocIQRoot))(result)

这会将数据解析为List,而你然后可以在快速 foreach 循环中读取对象。



另外,我写了一篇关于这个主题的文章,你可以查看,从零到英雄在JSON与C# [ ^ ]。我探讨了一些案例和场景,您可以在文章的质量保证部分找到更多提示和提示。

This will parse the data as a List, and you can then read the objects in a quick foreach loop.

Also, I wrote an article on this topic that you can check out, From zero to hero in JSON with C#[^]. I explores some cases and scenarios, and you can find some more tips and hints in the QA section under the article.


这篇关于Newtonsoft json反序列化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆