Json.net反序列化对象很方便,但我不知道如何使用它来反序列化一些简单的类型,比如string、int。
不知道我做的对不对,请帮忙,谢谢!
WCF 返回字符串看起来像
{"PingResult":100}
如果调用
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)
最佳答案
你不是在反序列化一个整数,而是一个包含整数属性的对象。您需要为反序列化提供这样一个类,例如:
class Ping
{
public int PingResult {get; set;}
}
然后调用
Ping ping = JsonConvert.DeserializeObject<Ping>(jsonString);
int result = ping.PingResult;
另一种方法是使用 JObject api :
string json="{\"PingResult\":100}";
JObject jo = JObject.Parse(json);
JToken jToken = jo["PingResult"];
int result = (int)jToken;
关于json - 如何使用 json.net 反序列化简单类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18126576/