Saturday, April 18, 2015

Working with JSON in IBM BPM

Now a days REST protocol has become very popular for interaction between various system. REST services support both json as well as xml as i/o. In this post, I would like to illustrate with an example on how to parse the json response / json object to retrieve the data and assign it to a tw variable by using json2.js file.
Let us first attach the file json2.js to the files sections under server files as shown below.

Figure 1



Now let create a complex variable type to hold the parsed data from json. In this example, let us consider the below complex variable structure.

Figure 2

Below show is the json structure which we will be using in this example.
var deepObject = {
        "user" : {
          "name": "Luís Landeiro Ribeiro",
          "age": 28,
          "sex": "M",
          "interests": [ "Technology", "Mountain Biking", "People" ]
        }
    };
This json object can be converted to string by using JSON.Stringify(). Below script line can be used to serialize this json to string.

var jsonString = JSON.stringify(deepObject);

Below is the code which can be used to convert the serialized json string to the json Object.

var newObject = JSON.parse(jsonString);
Below is the code which can be used to get the data from the json object and add the data to the tw variable.

   tw.local.user=new tw.object.User();
   tw.local.user.name=newObject.user.name;
   tw.local.user.age=String(newObject.user.age);
   tw.local.user.sex=newObject.user.sex;
   tw.local.user.interests=new tw.object.listOf.String();

   for(var i=0;i<newObject.user.interests.length ;i++){
       tw.local.user.interests[i]=newObject.user.interests[i];
   }

Below is the screen shot of the server script of the complete json parsing script.

Figure 3

Let us feed this variable tw.local.user to the coach to see the data in the variable after the json is parsed.

Figure 4

Hope this help full !!!
You might also like to see the post on how to parse xml in ibm bpm.

Thanks for stopping by. If you like this post leave a comment, share it and do a g +1.




6 comments:

  1. I am able to download the file from link. Are you getting some error when you try to download?

    ReplyDelete
  2. It seems like it is jsCache.js instead of json2.js when I tried to download

    ReplyDelete
  3. Thanks for pointing that Nguyen. I will update that. You can also find json2.js on web. please download and use it meanwhile

    ReplyDelete
  4. How to create restful service in bpm whi ch accepts media type as a application/json and a request object can help me how to create and to send response with same media type

    ReplyDelete
  5. Hi There, useful article, but it works only if you have a Business Object representing your JSON file. In case of complex JSON you want to parse the json and create a JS object and then assign some attribute to simpler business object. Having a working sample of this part would help

    ReplyDelete