简体   繁体   中英

How do I deserialize to object with json.net (instead of JObject)

Using json.net this test fails by default:

JsonConvert.DeserializeObject(
    JsonConvert.SerializeObject(new object()), typeof(object)
).ShouldBeOfType<object>(); // actual type is JObject

Is there a way to change this behavior, so it deserializes to the actual requested type?

You have a degenerate test case there. If you instruct Json.Net to deserialize into type object , you are telling it that the JSON could represent any possible object. So it will choose to use a JObject in that case, since you were not specific and a JObject can handle any JSON object. It is not expecting that you want to deserialize into a literal empty object instance, because that is not a very useful thing to do. If the JSON contained any data at all, you would not be able to access that data after the deserialization: object has no properties!

You can fix your test by creating an empty class Foo and using that in place of object :

JsonConvert.DeserializeObject(
    JsonConvert.SerializeObject(new Foo()), typeof(Foo)
).ShouldBeOfType<Foo>();

If you really do need to force Json.Net to deserialize into an empty object instance whenever object is specified as the type, you can do it using a custom JsonConverter like this:

public class EmptyObjectConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(object);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);  // consume the JSON object from the reader 
        return token.Type == JTokenType.Null ? null : new object();
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Then pass an instance of the converter to JsonConvert.DeserializeObject() :

JsonConvert.DeserializeObject(
    JsonConvert.SerializeObject(new object()), 
    typeof(object),
    new EmptyObjectConverter()
).ShouldBeOfType<object>();

Fiddle: https://dotnetfiddle.net/7xZ7tm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM