如何用json.net反序列化简单类型?

时间:2013-08-08 12:53:04

标签: json json.net

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)

2 个答案:

答案 0 :(得分:3)

您没有反序列化整数,而是包含整数属性的对象。您需要为反序列化提供这样的类,例如:

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;

答案 1 :(得分:0)

反序列化存储为字符串的简单类型(此问题的标题)可以像这样完成:

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

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

这应该处理所有基本类型,浮点数,整数,字符串等。