c# - Populating non-serializable object with Json.NET -


in test want populate object (a view model) json string. example, target object has property:

public string query { get; set; } 

so want able this:

var target = ...; jsonconvert.populateobject(target, "{ 'query': 'test' }"); 

however, query property not being set. debugging through code, appears properties on target ignored because member serialization opt-in. since target class not data contract , not populated in way outside of unit tests, cannot opt member serialization via attributes.

i can't find way modify member serialization outside. hoping overload of populateobject taking settings allow me so, don't see way so.

how can ensure populateobject sets properties on target though isn't data contract?

you can create contractresolver interprets classes opt-out rather opt-in:

public class optoutcontractresolver : defaultcontractresolver {     protected override ilist<jsonproperty> createproperties(type type, memberserialization memberserialization)     {         return base.createproperties(type, memberserialization.optout);     } } 

and use like:

[jsonobject(memberserialization = memberserialization.optin)] //[datacontract] -- works. public class testclass {     public string query { get; set; } // not serialized default since 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 initial value 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 value populated -- no assert.          debug.writeline(jsonconvert.serializeobject(test, formatting.indented, settings));     } } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -