Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize simple type with json.net?

Tags:

json

json.net

Json.net is handy to deserialize object, but I don't know how to use it to deserialize some simple type, such as string, int.

Not sure if I did it right, please help, thank you!

WCF return string looks like

{"PingResult":100}

If call

int result = JsonConvert.DeserializeObject<int>(jsonString);

Unity throw

JsonReaderException: Error reading integer. Unexpected token: StartObject. Path '', line 1, position 1.
Newtonsoft.Json.JsonReader.ReadAsInt32Internal ()
Newtonsoft.Json.JsonTextReader.ReadAsInt32 ()
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType (Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonContract contract, Boolean hasConverter)
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, Boolean checkAdditionalContent)
like image 483
zhuchun Avatar asked Sep 05 '25 03:09

zhuchun


2 Answers

You are not deserializing an integer, but an object containing an integer property. You need to provide such a class for the deserialization to work, for example:

class Ping
{
    public int PingResult {get; set;}
}

and then call

Ping ping = JsonConvert.DeserializeObject<Ping>(jsonString);
int result = ping.PingResult;

Another approach would be to use the JObject api:

string json="{\"PingResult\":100}"; 
JObject jo = JObject.Parse(json); 
JToken jToken = jo["PingResult"];
int result = (int)jToken;
like image 164
elolos Avatar answered Sep 07 '25 21:09

elolos


Deserializing a simple type stored as a string (the title of this question) can be done like this:

    private static T ParseStringToTypedValue<T>(string value)
    {
        if (typeof(T) == typeof(string))
        {
            return JToken.Parse($"\"{value}\"")
                         .Value<T>();
        }

        return JToken.Parse(value)
                     .Value<T>();
    }

This should handle all the basic types, floats, ints, strings etc..

like image 38
user230910 Avatar answered Sep 07 '25 22:09

user230910