How can I populate an existing object from a JToken (using Newtonsoft.Json)?

According to http://www.newtonsoft.com/json/help/html/PopulateObject.htm you can update an existing instance with the values โ€‹โ€‹defined in the JSON string. My problem is that the data I have to fill in has already been parsed into a JToken object. My current approach looks something like this:

Private Sub updateTarget(value As JToken, target as DemoClass) Dim json As String = value.ToString(Formatting.None) JsonConvert.PopulateObject(json, target) End Sub 

Is there a better way to do this, not to โ€œcancelโ€ the parsing that was already done when creating the JToken in the first place?

+7
json c #
source share
1 answer

Use JToken.CreateReader() and pass JsonSerializer.Populate reader. The reader has returned JTokenReader , which JTokenReader through the previously existing JToken hierarchy instead of serializing to a string and parsing.

Since you noted your c# question, the c# extension method that does the job is used here:

 public static class JsonExtensions { public static void Populate<T>(this JToken value, T target) where T : class { using (var sr = value.CreateReader()) { JsonSerializer.CreateDefault().Populate(sr, target); // Uses the system default JsonSerializerSettings } } } 

I think this is the equivalent of VB.NET:

 Public Module JsonExtensions <System.Runtime.CompilerServices.Extension> Public Sub Populate(Of T As Class)(value As JToken, target As T) Using sr = value.CreateReader() ' Uses the system default JsonSerializerSettings JsonSerializer.CreateDefault().Populate(sr, target) End Using End Sub End Module 
+11
source share

All Articles