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

c# - JSON.NET Why does it Add to List instead of Overwriting?

public class MyClass {
    public List<int> myList = new List<int> { 1337 };
    public MyClass() {}
}

var myClass = JsonConvert.DeserializeObject<MyClass>("{myList:[1,2,3]}");
Console.WriteLine(string.Join(",", myClass.myList.ToArray())); //1337,1,2,3

Why does it display 1337,1,2,3 instead of 1,2,3? Is there a way/setting to make JSON.NET overwrite List instead of adding elements to it?

I need a solution that doesn't modify the constructor.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you don't want this behavior, you can change it by passing in a JSONSerializerSettings object that specifies you don't want to reuse existing objects in the instance's members:

var settings = new JsonSerializerSettings
{
    ObjectCreationHandling = ObjectCreationHandling.Replace
};

var myInstance = JsonConvert.DeserializeObject<MyClass>("{myList:[1,2,3]}", settings);

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

Just Browsing Browsing

1.4m articles

1.4m replys

5 comments

57.0k users

...