0

I've got an ASP.NET MVC site with a controller action that is returning JSON. The JSON is serialized via Newtonsoft's JSON.NET, with

' This is VB, even though it looks very C#-like.
result = 
JsonConvert.SerializeObject(
    Data, Formatting.Indented, 
    New JsonSerializerSettings With {
        .ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
        .PreserveReferencesHandling = PreserveReferencesHandling.Objects
    })

Note the .PreserveReferencesHandling = PreserveReferencesHandling.Objects.

The consumer of this serialized data is javascript in the browser.

So how can I get the consumer, javascript, to play nice with the references that JSON.NET generated? I don't have to scan the entire object hierarchy looking for the object that has the correct $id property, do I?

Sam Axe
  • 33,313
  • 9
  • 55
  • 89
  • Show us the object generated – Weedoze Oct 20 '16 at 07:47
  • 1
    Similar or identical: [Resolve circular references from JSON object](https://stackoverflow.com/questions/15312529) and [How to restore circular references (e.g. “$id”) from Json.NET-serialized JSON?](https://stackoverflow.com/questions/21686499) and [Is there a Jquery function that can take a #ref id value from a parsed JSON string and point me to the referenced object?](https://stackoverflow.com/questions/10747341). – dbc Oct 20 '16 at 08:16
  • 1
    Thank you @dbc, those links set me on a good path. – Sam Axe Oct 20 '16 at 22:56
  • 1
    Josh Mouch's [answer here](http://stackoverflow.com/a/35213365/74015) was exactly what I was looking for. – Sam Axe Oct 21 '16 at 06:57

1 Answers1

-3

First of all you don't have to manually serialize the object into JSON. You can use JsonResult like this:

public JsonResult GetResult()
{
    string myObject = "test";
    return Json(myObject, JsonRequestBehavior.AllowGet);
}

Now answering your question: In the JavaScript you will get whole JSON object, just get from it what you want (better is just to send what you want without redundant data). Here is piece of JS code:

$.get(URL, function (JSON) {
    ...                
});

JSON will be the object which you sen in the GetResult() action.

Dawid Rutkowski
  • 2,658
  • 1
  • 29
  • 36