Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

c#

vb.net

According to http://www.newtonsoft.com/json/help/html/PopulateObject.htm you can update an existing instance by values defined in a JSON-string. My problem is that the data I have to populate the object 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 accomplish this without having to "revert" the parsing that was already done when creating the JToken in the first place?

like image 323
mike Avatar asked May 13 '15 16:05

mike


People also ask

What is the use of Newtonsoft JSON?

The Newtonsoft. JSON namespace provides classes that are used to implement the core services of the framework. It provides methods for converting between . NET types and JSON types.

What does JToken parse do?

Parse() to parse a JSON string you know to represent an "atomic" value, requiring the use of JToken. Parse() in such a case. Similarly, JToken. FromObject() may be used to serialize any sort of c# object to a JToken hierarchy without needing to know in advance the resulting JSON type.

What is JToken in C#?

JToken is the abstract base class of JObject , JArray , JProperty , and JValue , which represent pieces of JSON data after they have been parsed. JsonToken is an enum that is used by JsonReader and JsonWriter to indicate which type of token is being read or written.


1 Answers

Use JToken.CreateReader() and pass the reader to JsonSerializer.Populate. The reader returned is a JTokenReader which iterates through the pre-existing JToken hierarchy instead of serializing to a string and parsing.

Since you tagged your question c#, here's a c# extension method that does the job:

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
        }
    }
}

And the equivalent in 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 
like image 180
dbc Avatar answered Sep 18 '22 08:09

dbc