将数据从 JSON 字符串覆盖到现有对象实例 [英] Overlay data from JSON string to existing object instance

查看:22
本文介绍了将数据从 JSON 字符串覆盖到现有对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想反序列化一个 JSON 字符串,它不一定包含每个成员的数据,例如:

I want to deserialize a JSON string which does not necessarily contain data for every member, e.g:

public class MyStructure
{
   public string Field1;
   public string Field2;
}

假设我有一个实例:

Field1: "data1"
Field2: "data2"

然后我反序列化一个字符串:

and I deserialize a string:

{ "Field1": "newdata1" }

结果应该是

Field1: "newdata1"
Field2: "data2"

Framework JavascriptSerializerJSON.NET 都在它们的反序列化方法中返回新对象,所以我能想到的直接这样做的唯一方法是比较反序列化的对象使用反射的现有方法似乎有很多不必要的开销.理想情况下,某些软件会有一个方法,在该方法中我传递了一个对象的现有实例,并且只有那些存在于字符串中的成员才会被更新.这里的重点是我希望能够仅将已更改的数据传递到服务器,并更新现有对象.

Framework JavascriptSerializer and JSON.NET both return new objects in their deserialize methods, so the only way I can think of doing this directly would be to compare the deserialized object with the existing one using reflection which seems like a lot of unnecessary overhead. Ideally, some software would have a method in which I passed an existing instance of an object, and only those members which existed in the string would get updated. The point here is that I would like to be able to pass only data which has changed to the server, and update an existing object.

是否可以使用这两种工具中的任何一种,如果不能,是否有关于如何解决问题的建议?

Is this possible using either of these tools, and if not, any suggestions on how to approach the problem?

推荐答案

在浏览源代码之后(比阅读文档容易多了,嗯?)JSON.NET 正是我想要的已经:

After poking around the source code (so much easier than reading the documentation, eh?) JSON.NET does exactly what I want already:

JsonConvert.PopulateObject(string, object)

请参阅Json.NET:填充对象

这篇关于将数据从 JSON 字符串覆盖到现有对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆