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
178 views
in Technique[技术] by (71.8m points)

c# - Overlay data from JSON string to existing object instance

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

Suppose I have an instance:

Field1: "data1"
Field2: "data2"

and I deserialize a string:

{ "Field1": "newdata1" }

The result should be

Field1: "newdata1"
Field2: "data2"

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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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)

See Json.NET: Populate an Object


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

...