Skip to main content

Notifications

Announcements

No record found.

Finance | Project Operations, Human Resources, ...
Unanswered

How to deserialize the JSON response in AX 2009

(0) ShareShare
ReportReport
Posted on by 745

Hi,

 Please let me know the code sample to deserialize or read the response values.I was able to read the first level of value but not the next level or the Array level.

Provided a bit of response sample that i need to deserialize.From below response,I was able to deserialize and get the value for A and return Value1,But i dont how to deserialize the other values B,B1,C1,D,E,F,F1,Email etc.Please help me with any sample code

{"data":
{"A":"value1=","B":{"B1":{"ValueB1":[{"c1":"Test c1","c2":"c2 value"}]},
"D":{},
"E":{}},
"F":[{"F1":"F1 value","F2 lang":"en"}],
"email":"testEmail id",
"tokens":{"G1_token":"test token value"},
"name":"Test name","phone":"123456"}}

  • Martin Dráb Profile Picture
    Martin Dráb 230,253 Most Valuable Professional on at
    RE: How to deserialize the JSON response in AX 2009

    First of all, explain what you meant about the hardcoded values. Are we able to refer to element names, such as B1? If not, we're wasting time here, because your whole design is wrong. If you know the element names at design time and you merely want to avoid hard-coding them as text, let me remind you that I gave you a solution for that at the very beginning - and you rejected it and used strings instead. My suggestiong was generating classes for JSON elements; it was disacussed in your other thread How to read and pass the values Json String in AX 2009,Axapta Map.

    Regarding your code, your output has nothing to do with your goal. Converting bJObj to string and showing it is nothing like iterating elements of valueB1Array.

    There are several ways how you could iterate array elements; let's use an enumerator (I hope this works in AX 2009):

    System.Collections.IEnumerator enumerator = valueB1Array.GetEnumerator();
    
    while (enumerator.MoveNext())
    {
    	itemJObj = enumerator.get_Current();
    }

  • Divya Lakshmi Profile Picture
    Divya Lakshmi 745 on at
    RE: How to deserialize the JSON response in AX 2009

    Hi Martin,

     Below is the code ,I have used,from your provided example.

      

    rootJObj = Newtonsoft.Json.Linq.JObject::Parse(response);
            dataJObj = rootJObj.get_Item('data');
            bJObj = dataJObj.get_Item('B');
            valueB1Array = bJObj.get_Item('ValueB1');
            childCount = valueB1Array.get_Count();
            value = bJObj.ToString();
            info(strfmt("%1",value));
            info(strfmt("%1",childCount));

    The result ,I Got from this Job and Info is as follows.

    info 1:

    ******

    {
    "B1": {
    "ValueB1": [
    {
    "c1": "Test c1",
    "c2": "c2 value"
    }

    },
    "D": {},
    "E": {}
    }

    Info 2

    ******

    1

    So here,as you said, I want to know How to print the array values  i.e B1'value ,c1's value..I want to know how to iterate the array and its values:

    I want to display or print info like the below

    A  =  value1

    B = B1

           B1 =  Value B1 

           Value B1 :

                 c1  =Test c1
                c2  =c2 value

    D = ""

    E = ""

  • Martin Dráb Profile Picture
    Martin Dráb 230,253 Most Valuable Professional on at
    RE: How to deserialize the JSON response in AX 2009

    What exactly do you mean by saying that you need to avoid hardcoding node names?

    Let me remind you your code:

    reader.getStringNode(strfmt("data.A", i));

    Are you now saying that your code doesn't meet your requirements, because it contains references to 'data' and 'A'? And therefore your approach is wrong from the very beginning?

    Or did you mean something else?

    Regarding your other questions, please let me remind you that we can't help if you don't give us enough information. Instead of just saying "I wrote some code and I can't return values", show us the code and explain what problem you have with it. Also, you look at my code above. It already shows how you can get ValueB1 (not the count of B1, as you seem to claim). Iterating the array will be the next step, when you're able to do the first step and if your actual requirements aren't completely different.

  • Divya Lakshmi Profile Picture
    Divya Lakshmi 745 on at
    RE: How to deserialize the JSON response in AX 2009

    Hi,

     I was able to retrieve the count of B1 ,returns the count 1 considering "ValueB1",But i couldn't return the nodes c1 and its values or couldn't return the value/String  as "ValueB1" for B1.....Likewise i was able to return the string value for B ....returns {"B1":{"ValueB1":[{"c1":"Test c1","c2":"c2 value"}]}

    Please let me know how to extract the values for B1,c1 etc...Without hardcoding the node name or string name.

  • Martin Dráb Profile Picture
    Martin Dráb 230,253 Most Valuable Professional on at
    RE: How to deserialize the JSON response in AX 2009

    I think that using JsonReader class from that blog post is actually making things more difficult for you, because it's written for a different purpose. Let's ignore it, at least for know. Try something like this instead:

    Newtonsoft.Json.Linq.JObject rootJObj;
    Newtonsoft.Json.Linq.JObject dataJObj;
    Newtonsoft.Json.Linq.JObject bJObj;
    Newtonsoft.Json.Linq.JObject b1JObj;
    Newtonsoft.Json.Linq.JArray valueB1Array;
    int childCount;
    ;
    rootJObj = Newtonsoft.Json.Linq.JObject::Parse(json);
    dataJObj = rootJObj.get_Item('data');
    bJObj = dataObj.get_Item('B');
    valueB1Array = bJObj.get_Item('ValueB1');
    childCount = valueB1Array.get_Count();

  • Divya Lakshmi Profile Picture
    Divya Lakshmi 745 on at
    RE: How to deserialize the JSON response in AX 2009

    Hi,

    Could you please help to fix the code or rewrite the code to extract B's Value.

    Because ,I tried directly to find data.B or to B ,But still it didn't find anything

  • Martin Dráb Profile Picture
    Martin Dráb 230,253 Most Valuable Professional on at
    RE: How to deserialize the JSON response in AX 2009

    I immediately see two problems:

    • Your code assumes that B is a child of A, which isn't true.
    • And it assumes that B is string, which isn't true either. B contains an object. You should get JObject representing B and get ValueB1 from it.

    By the wat, please don't forget using Insert > Code to paste source code.

  • Divya Lakshmi Profile Picture
    Divya Lakshmi 745 on at
    RE: How to deserialize the JSON response in AX 2009

    Hi,

    Yes,I don't know how to extract values for B,C and so on.

    I tried same as below. and of no use since the format "data.A.B" is wrong I think

    if(reader.isFound(strfmt("data.A.B", i)))

    {

    strResult = reader.getStringNode(strfmt("data.A.B", i));

    info(strfmt("%1", strResult));//, intResult));

    }

  • Martin Dráb Profile Picture
    Martin Dráb 230,253 Most Valuable Professional on at
    RE: How to deserialize the JSON response in AX 2009

    You showed code for getting A, but - if I understand it correctly - you said that it works. So it's not that interesting.

    But you're unable to extract values of B, right? Therefore that's what we should focus on. Show us your code for retrieving B and explain what problem you have with it. For example, are you able to get JObject representing B? Are you able to access its ValueB1 property?

  • Divya Lakshmi Profile Picture
    Divya Lakshmi 745 on at
    RE: How to deserialize the JSON response in AX 2009

    Hi MArtin,

    I have copied the same code from the link and pasted here.Please help me to modify the code that would return the value for the sample response i have attached in my question.

    class JsonReader
    {
        Newtonsoft.Json.Linq.JObject    jObject;
    }
    
    public void loadJson(str _json)
    {
        ;
    
        jObject = Newtonsoft.Json.Linq.JObject::Parse(_json);
    }
    
    public static JsonReader parseJson(str _json)
    {
        JsonReader reader = new JsonReader();
        ;
    
        reader.loadJson(_json);
        return reader;
    }
    
    private anytype traversePath(str                               path,
                                 Newtonsoft.Json.Linq.JContainer   obj = jObject)
    {
        List                            pathElements;
        ListEnumerator                  le;
        Newtonsoft.Json.Linq.JValue     value;
        Newtonsoft.Json.Linq.JToken     token;
        Newtonsoft.Json.Linq.JTokenType thisType,
                                        nestedType;
        Newtonsoft.Json.Linq.JObject    newObject;
        Newtonsoft.Json.Linq.JArray     newArray;
        str                             current,
                                        thisTypeString,
                                        nestedTypeString;
     
        #define.JObject("Newtonsoft.Json.Linq.JObject")
        #define.JArray ("Newtonsoft.Json.Linq.JArray")
     
        ;
     
        pathElements = strSplit(path, @".\/");
     
        le = pathElements.getEnumerator();
     
        if (le.moveNext())
        {
            current = le.current();
     
            thisType = obj.GetType();
            thisTypeString = thisType.ToString();
     
            switch (thisTypeString)
            {
                case #JObject:
                    token = obj.get_Item(current);
                    break;
                case #JArray:
                    token = obj.get_Item(str2int(current) - 1);
                    break;
                default:
                    return null;
            }
     
            if (token)
            {
                nestedType = token.GetType();
                nestedTypeString = nestedType.ToString();
     
                if (nestedTypeString != #JObject && nestedTypeString != #JArray)
                {
                    switch (thisTypeString)
                    {
                        case #JArray:
                            return obj.get_Item(str2int(current) - 1);
                        case #JObject:
                            return obj.get_Item(current);
                        default:
                            return null;
                    }
                }
                 
                switch (nestedTypeString)
                {
                    case #JObject:
                        newObject = Newtonsoft.Json.Linq.JObject::FromObject(token);
                        return this.traversePath(strDel(path, 1, strLen(current)   1), newObject);
                    case #JArray:
                        newArray = Newtonsoft.Json.Linq.JArray::FromObject(token);
                        return this.traversePath(strDel(path, 1, strLen(current)   1), newArray);
                    default:
                        return null;
                }
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }
    
    
    public real getRealNode(str path)
    {
        return this.traversePath(path);
    }
    
    public int getIntNode(str path)
    {
        return this.traversePath(path);
    }
    
    public str getStringNode(str path)
    {
        return System.Convert::ToString(this.traversePath(path));
    }
    
    public boolean isFound(str _path)
    {
        return this.traversePath(_path) != null;
    }
    

    I couldn't retrieve B,C or D and other path elements and its values.

    Job...Code to retrieve the array of object results is 

    JsonReader  reader;
    str json,
    strResult;
    int i,
    intResult;
    ;

    json = "{\"object\":[{\"Property\":\"Alpha\",\"Value\":1},{\"Property\":\"Beta\",\"Value\":2},{\"Property\":\"Gamma\",\"Value\":3}
    }";

    reader = JsonReader::parseJson(json);

    for (i = 1; reader.isFound(strfmt("object.%1.Property", i)); i )
    {
    strResult = reader.getStringNode(strfmt("object.%1.Property", i));
    intResult = reader.getIntNode(strfmt("object.%1.Value", i));
    info(strfmt("%1 = %2", strResult, intResult));
    }

    My JSON repose string is 

    json = {
    "data": {
    "A": "value1=",
    "B": {
    "B1": {
    "ValueB1": [
    {
    "c1":"Test c1",
    "c2":"c2 value"
    }

    },
    "D":{},
    "E":{}
    },
    "F": [
    {
    "F1": "F1 value",
    "F2 lang": "en"
    }
    ,
    "email": "testEmail id",
    "tokens": {
    "G1_token":"test token value"
    },
    "name": "Test name",
    "phone": "123456"
    }
    }

    So,Here I have made slight change to retrieve my first level data that is to return A's value only

    if(reader.isFound(strfmt("data.A", i)))

    {

    strResult = reader.getStringNode(strfmt("data.A", i));

    info(strfmt("%1", strResult));//, intResult));

    }

    Please let me know how to retrieve the value for other nodes and forloop

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,253 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans