json.net, JsonReaderException: After parsing a value an unexpected character was encountered

StackOverflow https://stackoverflow.com/questions/22936600

  •  29-06-2023
  •  | 
  •  

Question

I am trying to deserialize a JSON array using Newtonsoft JSON. However, using the string received from the server, I am getting the following error:

Newtonsoft JSON, JsonReaderException: After parsing a value an unexpected character was encountered

If I hardcode the string in the deserialization, it is working just fine.

Here is the raw JSON. Received from server is identical to the hardcoded string when printing to console.

{"id":15,"username":"patrick"}

And the code deserializing it

JsonConvert.DeserializeObject<User>(jsonstring);

I suspect it has something to do with encoding.

What am I doing wrong?


User class by request

using UnityEngine;
using System.Collections;
using Newtonsoft.Json;
[JsonObject(MemberSerialization.OptOut)]
public class User{


        [JsonProperty]
        private int id;
        [JsonProperty]
        private string username;

        public User (int setId, string setName){
                id = setId;
                username = setName;
        }


        public string GetUsername(){
                return username;
        }

}
Was it helpful?

Solution

Well, what string you are trying to deserialize? I used the following code and didn't get any problems:

public static void Main()
{
      const string jsonString = "{ \"id\":15, \"username\":\"patrick\" }";
      User u = JsonConvert.DeserializeObject<User>(jsonString);
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top