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)
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;
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With