Strongly typed json results from ajax call-VBForums
Results 1 to 7 of 7

Thread: Strongly typed json results from ajax call

Hybrid View

  1. #1

    Thread Starter
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Strongly typed json results from ajax call

    In the success section of my ajax call I'm able to set variables based on the index of the raw json that's returned from my WCF RIA service like this:

    Code:
                    var results = data.GetCorrespondenceByIDResult;
                    var correspondence = results.RootResults[0];
                    var contact = results.IncludedResults[0];
                    var letter = results.IncludedResults[1];
    The problem I run into is that sometimes I have additional objects returned (The organization for the contact via a go between table called contactorganization) that throws off the index of the letter variable.

    When looking at the results returned from the service I'm able to see that each of the items has is denoted as a stongly typed object in the form of

    "__type":"Letter:#CRM.Data.Models"
    Rather than get the results by index how can I look for the type and assign the variables based on that?

  2. #2
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    15,870

    Re: Strongly typed json results from ajax call

    If they are not JS arrays but are javascript objects - which you can access by "name" like this

    var letter = results.IncludedResults["somename"];

    I do things like this

    Code:
    if (typeof objInto["acs-reader-" + strSC] == "undefined") {
        objInto["acs-reader-" + strSC] = {};
    }
    Do you have FIREBUG installed in the browser (I am assuming you use Firefox)??

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  3. #3

    Thread Starter
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: Strongly typed json results from ajax call

    Here's my WCF RIA service query:

    Code:
            public Correspondence GetCorrespondenceByID(int correspondenceID)
            {
                return this.ObjectContext
                    .Correspondences
                    .Include("PhoneCalls")
                    .Include("InPersonVisits")
                    .Include("Letters")
                    .Include("Letters.Files")
                    .Include("Emails")
                    .Include("InvitationDetails2")
                    .Include("Contact")
                    .Include("Contact.ContactOrganizations.Organization")
                    .Where(c => c.ID == correspondenceID).FirstOrDefault();
            }
    All of the ugly includes are necessary when returning JSON but not when using the DomainDataSource which is weird.

    Here's an example of the

    {"GetCorrespondenceByIDResult":{"TotalCount":-1,"IncludedResults":[{"__type":"Contact:#CRM.Data.Models","CreatedBy":"user@domain.com","CreatedDate":"\/Date(1330989421240-0700)\/","FirstName":"Joe","ID":7062,"IsActive":true,"JobTitle":null,"LastName":"Smith","PeopleID":7757,"St ateAgencyID":null,"StateAgencyRoutingID":null},{"__type":"Letter:#CRM.Data.Models","CorrespondenceID ":114,"Details":"Some details about the incident","ID":6937},{"__type":"ContactOrganization:#CRM.Data.Models","ContactID":7062,"CreatedBy":" user@domain.com","CreatedDate":"\/Date(1330989427377-0700)\/","OrganizationID":558},{"__type":"Organization:#CRM.Data.Models","CreatedBy":"user@domain.com","Cre atedDate":"\/Date(1330989419727-0700)\/","IsActive":true,"OrganizationID":558,"OrganizationName":"Some organization name","StateAgencyID":null}],"RootResults":[{"ContactID":7062,"CreatedBy":"user@domain.com","CreatedDate":"\/Date(1328079600000-0700)\/","ID":114,"SituationID":4118}]}}
    I'm not a master at JSON but it looks like both RootResults and IncludedResults are both arrays.

    Firebug seems to confirm this saying GetCorrespondenceByIDResult is an object with TotalCount -1 IncludedResults[4] and RootResults[1]

  4. #4
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    15,870

    Re: Strongly typed json results from ajax call

    First - I like your use of the term "strongly typed" - json and javascript couldn't be further from that paradigm

    Second - nice site to both validate and "re-align" JSON for visual view is this

    http://jsonlint.com/

    And it shows your JSON string as the image below.

    The OBJECT GetCorrespondenceByIDResult has many object pairs in it - like

    "TotalCount": -1

    and

    "IncludedResults": [

    and as you see - "IncludedResults" is an array. And it's an array of OBJECT's with object pairs within...

    JS does not have a native way to find an "array element" by some value in it's content - you will need to write a loop on that array - something like

    Code:
    var contact = "";
    for (var i = 0; i < results.IncludedResults.length; i++) {
         if (results.IncludedResults[i]["__type"] == "Contact:#CRM.Data.Models") {
              contact = results.IncludedResults[i].LastName + ' ' + results.IncludedResults[i].FirstName;
              // do whatever else with this array element
         }
    }
    Attached Images Attached Images  
    Last edited by szlamany; Mar 6th, 2012 at 05:12 PM.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  5. #5

    Thread Starter
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: Strongly typed json results from ajax call

    Quote Originally Posted by szlamany View Post
    First - I like your use of the term "strongly typed" - json and javascript couldn't be further from that paradigm
    Oops, was working with knockoutjs modeling on another project before posting the question.

    Quote Originally Posted by szlamany View Post
    Code:
    var contact = "";
    for (var i = 0; i < results.IncludedResults.length; i++) {
         if (results.IncludedResults[i]["__type"] == "Contact:#CRM.Data.Models") {
              contact = results.IncludedResults[i].LastName + ' ' + results.IncludedResults[i].FirstName;
              // do whatever else with this array element
         }
    }
    Ah, was missing ["__type"] when trying to loop through the results. Knew it was something simple.

    Refactored it to:

    Code:
        function getIncludedResultsByType(results, type) {
            for (var i = 0; i < results.IncludedResults.length; i++) {
                if (results.IncludedResults[i]["__type"] === type) {
                    return results.IncludedResults[i];
                }
            }
        }
    So it can be called like:

    Code:
    var contact = getIncludedResultsByType(results, "Contact:#CRM.Data.Models");
    var letter = getIncludedResultsByType(results, "Letter:#CRM.Data.Models");

  6. #6
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    15,870

    Re: Strongly typed json results from ajax call

    I didn't realize you wanted to "process" the "whole object"...

    Nice function...

    [btw] I have to remember to use the === operator instead of == ... to many languages too little time...[/btw]

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  7. #7

    Thread Starter
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: Strongly typed json results from ajax call

    Yeah, I need the whole object. Now I've got a nice little function I can reuse though. Handy since I've got a couple hundred places in the application I can apply it.

    Thanks.

    Quote Originally Posted by szlamany View Post
    too many languages too little time...
    Tell me about it. Got a project coming where they require a Java and then another proof of concept one using Go.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.