Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

c# - 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...