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

c# - Json.Net adding $id to EF objects despite setting PreserveReferencesHandling to "None"

I've already looked at how to remove $id during JSON serialization but the answers given do not seem to be working for me and I hope someone can figure out what I am doing wrong.

Here is my code:

return JsonConvert.SerializeObject(target, new JsonSerializerSettings {
    NullValueHandling = NullValueHandling.Include,
    PreserveReferencesHandling = PreserveReferencesHandling.None,
    ContractResolver = new CustomContractResolver(),
    Converters = CustomConverters
});

The output from this is still coming out with $id's, BUT, only on Entity Framework objects, is this by design? If so, is there any way to prevent those $id's on Entity Framework objects?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The custom ContractResolver setting overrides the PreserveReferencesHandling setting.

In your implementation of DefaultContractResolver/IContractResolver, add this;

public override JsonContract ResolveContract(Type type) {
    var contract = base.ResolveContract(type);
    contract.IsReference = false;
    return contract;
}

This behaves similarly to the PreserveReferencesHandling.None setting without a custom ContractResolver.


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

...