Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Unexpected token: StartObject" when Deserializing with Json.net

Tags:

json

c#

json.net

I have the following JSON that a C# WebClient returned:

"\n\n\n{\n \"resultCount\":1,\n \"results\": [\n{\"wrapperType\":\"artist\", \"artistType\":\"Artist\", \"artistName\":\"Jack Johnson\", \"artistLinkUrl\":\"http://itunes.apple.com/us/artist/jack-johnson/id909253?uo=4\", \"artistId\":909253, \"amgArtistId\":468749, \"primaryGenreName\":\"Rock\", \"primaryGenreId\":21}]\n}\n\n\n"

or, more clearly:

{
   "resultCount ":1,
   "results ":[
      {
         "wrapperType ":"artist ",
         "artistType ":"Artist ",
         "artistName ":"Jack Johnson ",
         "artistLinkUrl ":"http://itunes.apple.com/us/artist/jack-johnson/id909253?uo=4 ",
         "artistId ":909253,
         "amgArtistId ":468749,
         "primaryGenreName ":"Rock ",
         "primaryGenreId ":21
      }
   ]
}

I've tried deserializing this to a class, like so:

 thejsonresult = JsonConvert.DeserializeObject<JsonResult>(WebRequest.Json);

but received the following error:

Error reading string. Unexpected token: StartObject. Line 7, position 2.

I'm pretty lost and can't find any documentation on this. Anyone got a clue?

like image 456
jbkkd Avatar asked Sep 08 '26 19:09

jbkkd


2 Answers

I believe the problem is actually to be found in the class to which you are attempting to deserialise.

The wrapper property you have is not being deserialised to correctly. If it is an object in your class, then it should work, but if it is a string, which I am guessing, then the Json deserialiser will try to deserialise it and find it's not a string.

like image 121
David Avatar answered Sep 11 '26 08:09

David


I recently ran into the same type of de-serializing exception, “Unexpected token: StartObject”, using the string from the serialization result.

Seems the property declaration of the target cannot be the same name as the object type. In my case the object being de-serialized had a property of ZipCode which was a class of ZipCode.

Ultimately, changing the property name to something other than the class name resolved the exception.

like image 36
user5606561 Avatar answered Sep 11 '26 09:09

user5606561



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!