简体   繁体   中英

Populating non-serializable object with Json.NET

In a test I want to populate an object (a view model) from a JSON string. For example, the target object has this property:

public string Query { get; set; }

So I want to be able to do this:

var target = ...;
JsonConvert.PopulateObject(target, "{ 'Query': 'test' }");

However, the Query property is not being set. Debugging through the code, it appears that properties on target are ignored because member serialization is opt-in. Since the target class is not a data contract and is not populated in this way outside of unit tests, I cannot opt it into member serialization via attributes.

I can't find a way to modify the member serialization from the outside. I was hoping the overload of PopulateObject taking settings would allow me to do so, but I don't see any way to do so.

How can I ensure PopulateObject sets properties on my target even though it isn't a data contract?

You can create a ContractResolver that interprets all classes as opt-out rather than opt-in:

public class OptOutContractResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        return base.CreateProperties(type, MemberSerialization.OptOut);
    }
}

And then use it like:

[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
//[DataContract] -- also works.
public class TestClass
{
    public string Query { get; set; } // Not serialized by default since this class has opt-in serialization.

    public static void Test()
    {
        var test = new TestClass { Query = "foo bar" };
        var json = JsonConvert.SerializeObject(test, Formatting.Indented);
        Debug.Assert(!json.Contains("foo bar")); // Assert the initial value was not serialized -- no assert.
        Debug.WriteLine(json);

        var settings = new JsonSerializerSettings { ContractResolver = new OptOutContractResolver() };
        JsonConvert.PopulateObject("{ 'Query': 'test' }", test, settings);
        Debug.Assert(test.Query == "test"); // Assert the value was populated -- no assert.

        Debug.WriteLine(JsonConvert.SerializeObject(test, Formatting.Indented, settings));
    }
}

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