本文介绍了如何从JToken填充现有对象(使用Newtonsoft.Json)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 http://www.newtonsoft.com/json/help/html/PopulateObject.htm ,您可以通过JSON字符串中定义的值来更新现有实例.我的问题是,我必须填充该对象的数据已经被解析为JToken对象.我目前的方法是这样的:

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

是否有更好的方法来完成此任务,而不必首先还原在创建JToken时已经完成的解析?

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?

推荐答案

使用 JToken.CreateReader() ,然后将阅读器传递给 JsonSerializer.Populate .返回的读者是 JTokenReader 遍历先前存在的JToken层次结构,而不是序列化为字符串并进行解析.

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.

由于您标记了问题c#,因此这是完成任务的c#扩展方法:

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

认为这是等效的VB.NET:

I think this is the equivalent 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

这篇关于如何从JToken填充现有对象(使用Newtonsoft.Json)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:36