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

后端 未结 1 533
灰色年华
灰色年华 2020-12-07 01:19

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

1条回答
  •  余生分开走
    2020-12-07 01:24

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

    0 讨论(0)
提交回复
热议问题