2

Through an HttpResponseMessage MVC4 successfully sends an AngularJs controller $scope of GetAllFolders().

A Folder in the collection has among other things and association to the Photo class.

Folders can be folders of other folders (self-referencing).

Debugging shows from MVC4 side all is good and correct detail information was returned.

But through Angular/Json, certain properties are $ref tag and can not be seen, as example:

enter image description here

I do not care much for creating a method call on FkPhotoId and hit the server for the image name when I know it was already sent in the first response.

Any ideas?

UPDATE: SOLUTION

This code was added in the global.asax: (make sure you reference it in the start method)

    public static void ConfigureApi(HttpConfiguration config)
    {
        var json = config.Formatters.JsonFormatter;
        config.Formatters.Remove(config.Formatters.XmlFormatter);
        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 
    }

enter image description here

j0k
  • 22,600
  • 28
  • 79
  • 90
Bye
  • 2,814
  • 7
  • 25
  • 36
  • 3
    Please add your solution as an answer -- then this question won't show up on the "unanswered" list. You can (and should) also accept it. – Mark Rajcok Jan 12 '13 at 18:27
  • how to go about doing that? – Bye Jan 12 '13 at 19:54
  • In the textbox below, type in your answer, click the "Post Your Answer" button. (Optionally remove your solution from the question). Then click the checkmark next to your answer. – Mark Rajcok Jan 12 '13 at 19:57

3 Answers3

8

Resolution from OP (housecleaning - marking so can mark answered) This code was added in the global.asax: (make sure you reference it in the start method)

public static void ConfigureApi(HttpConfiguration config)
{
    var json = config.Formatters.JsonFormatter;
    config.Formatters.Remove(config.Formatters.XmlFormatter);
    config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 
}
Mark Nadig
  • 4,901
  • 4
  • 37
  • 46
1

I am tired of seeing this answer "Just disable stuff and work around it." It's lazy, it's wrong, and incredibly reductive to the usefulness of retaining this data.

This is a three part answer. The first part is to disable collection references and only retain objects.

In my case, I couldn't think of a scenario where I would be sharing collection references and the additional code is messy. If you need collection references WRITE THE CONSUMING FE LOGIC. Don't just disable it. It just happened that I didn't need it.

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

The second portion is here. I got this from another answer and added a tweak that was missing. (This is the original Resolve circular references from JSON object):

function resolveReferences(json) {
    if (!json)
        return json;

    if (typeof json === 'string')
        json = JSON.parse(json);

    var byid = {}, // all objects by id
        refs = []; // references to objects that could not be resolved
    json = (function recurse(obj, prop, parent) {
        if (typeof obj !== 'object' || !obj) // a primitive value
            return obj;
        if (Object.prototype.toString.call(obj) === '[object Array]') {
            for (var i = 0; i < obj.length; i++)
                // check also if the array element is not a primitive value
                if (typeof obj[i] !== 'object' || !obj[i]) // a primitive value
                    continue;
                else if ("$ref" in obj[i])
                    obj[i] = recurse(obj[i], i, obj);
                else
                    obj[i] = recurse(obj[i], prop, obj);
            return obj;
        }
        if ("$ref" in obj) { // a reference
            var ref = obj.$ref;
            if (ref in byid)
                return byid[ref];
            // else we have to make it lazy:
            refs.push([parent, prop, ref]);
            return;
        } else if ("$id" in obj) {
            var id = obj.$id;
            delete obj.$id;
            if ("$values" in obj) // an array
                obj = obj.$values.map(recurse);
            else // a plain object
                for (var prop in obj)
                    obj[prop] = recurse(obj[prop], prop, obj);
            byid[id] = obj;
        }
        return obj;
    })(json); // run it!

    for (var i = 0; i < refs.length; i++) { // resolve previously unknown references
        var ref = refs[i];
        ref[0][ref[1]] = byid[ref[2]];
        // Notice that this throws if you put in a reference at top-level
    }
    return json;
}

The second portion is to reprocess and reestablish circular dependencies prior to sending the data back. My FE is an angular app, so I am personally calling this in an injected HTTP interceptor prior to the ajax posts.(note I am checking for a property called "typeName" because all objects with that property are assumed to be objects that will be deserialized on the back end).

function processReferenceEstablishment(data) {
    if (!data || typeof (data) === 'function')
        return undefined;

    var processData = [];
    var tiers = {};
    var refKey = 1;
    if (Array.isArray(data)) {
        data = jQuery.extend([], data);
    } else {
        data = jQuery.extend({}, data);
    }


   

    var retVal = (function recurse(obj, tier) {
        tiers[tier] = tiers[tier] || {};
        tiers[tier].width = tiers[tier].width ? tiers[tier].width + 1 : 1;
        if (obj) {
            if (typeof obj !== 'object' || typeof (obj) === 'function') {
                return obj;
            }

            for (var key in data) {
                var val = data[key];
                if (key.indexOf("$") > -1 || typeof(val) === 'function') {
                    delete data[key];
                }
            }
            if (Array.isArray(obj)) {
                obj = jQuery.extend([], obj);
                for (var ix = 0; ix < obj.length; ix++) {
                    obj[ix] = recurse(obj[ix], tier);
                }
            }
            else if ('typeName' in obj) {
                if (obj.skipSend) {
                    return undefined;
                }
                obj = jQuery.extend({}, obj);
                var found = false;
                for (var pdIx = 0; pdIx < processData.length; pdIx++) {
                    var item = processData[pdIx];
                    if (item.id === obj.id && item.typeName === obj.typeName) {
                        found = true;
                        if (!item.jsonTier || item.jsonTier > tier) {
                            item.jsonTier = tier;
                            item.jsonWidth = tiers[tier].width;
                        }
                        if (tier === item.jsonTier && item.jsonWidth > tiers[tier].width) {
                            item.jsonWidth = tiers[tier].width;
                        }
                        if (tier > item.jsonTier || (tier === item.jsonTier && item.jsonWidth < tiers[tier].width)) {
                            return { $ref: item.$id.toString() };
                        }
                        break;
                    }
                }
                if (!found) {
                    obj.$id = refKey;
                    refKey++;
                    processData.push({$id:obj.$id, id: obj.id, typeName: obj.typeName, jsonTier: tier, jsonWidth: tiers[tier].width });
                }
                var keys = Object.keys(obj);
                keys.sort();
                for (var key in keys) {
                    key = keys[key];
                    obj[key] = recurse(obj[key], tier + 1);
                }
            }
        }
        return obj;
    })(data, 1);

    retVal = (function recurse(obj, tier) {
        tiers[tier] = tiers[tier] || {};
        tiers[tier].destWidth = tiers[tier].destWidth ? tiers[tier].destWidth + 1 : 1;
        if (typeof obj !== 'object' || !obj) {
            return obj;
        }
        if (Array.isArray(obj)) {
            for (var ix = 0; ix < obj.length; ix++) {
                obj[ix] = recurse(obj[ix], tier);
            }
        }
        else if ('typeName' in obj) {
            var found = false;
            for (var pdIx = 0; pdIx < processData.length; pdIx++) {
                var item = processData[pdIx];
                if (item.id === obj.id && item.typeName === obj.typeName) {
                    found = true;
                    if (item.jsonTier < tier || (item.jsonTier === tier && item.jsonWidth < tiers[tier].destWidth)) {
                        return { $ref: item.id.toString() };
                    }
                }
            }
            var keys = Object.keys(obj);
            keys.sort();
            for (var key in keys) {
                key = keys[key];
                obj[key] = recurse(obj[key], tier + 1);
            }
        }
        return obj;
    })(retVal, 1);
    return retVal;
}

Now, to be clear. My reestablishment of $ref and $id is often happening out of order and I get the odd collection object reference or navigation property object reference on the back end that comes back null. I am still working on that. I really need to pull down the NewtonSoft.JSON libraries and pull them apart to figure out what order to process the object graph in so I can eliminate the null references after deserialization.

To me, this is headed for a real solution instead of throwing in the towel and disabling circular references because of laziness.

0

Just to add my two cents. I had this extra line in my code that was also causing this issue

config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

Thanks digger69 for this one.

daudihus
  • 159
  • 1
  • 8