开发者

Using JSON.NET instead of the default WebMethod serialization

In a WebMethod I am using JSON.NET to manually serialize my object to avoid the entity framework circular reference problem.

I have the following code:

Dim qry = From m In entity.Mediators _
          Where m.MediatorNumber = mediatorNumber _
          Select m

For Each mediator In qry
    mediator.MediatorRestrictionsAvailabilities.Load()
    customMediator = mediator
Next

customJson = JsonConvert.SerializeObject(customMediator, Formatting.Indented)

The problem is that the result is not well开发者_运维知识库 formatted JSON and cannot be parsed on the client; it looks like this:

{"d":"{\r\n \"$id\": \"1\",\r\n \"MediatorId\": 922,\r\n \"AreaCode\": \"E \",\r\n \"PFCCode\": \"840 \",\r\n \"FirstName\": \"Joe\",\r\n \"LastName\": \"Smith\",\r\n

After doing some research I have learned that this is what happens when JSON is reserialized into JSON.

How do I do my own custom serialization without the default serializer getting in the way?


I had a similar problem a while back and here are the suggestions which I was given. My solution was that I did not need to serialize the object again into json as it was already being serialized.

Good luck and hope this helps some.


For the circular reference use this approach:

string json = JsonConvert.SerializeObject(
  infoToSerialize, Formatting.Indented,
  new JsonSerializerSettings{ ReferenceLoopHandling =
  ReferenceLoopHandling.Ignore
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜