OpenText product name changes coming to the community soon! Learn more.

Wikis - Page

Scripting: How to work with JSON payload in Binary/HTTP Virtual Service using C# Scripted Rule

0 Likes

In current version SV is using Newtonsoft.Json 3rd party library, which you can utilize in your C# scripted rules as well. Here is a basic example.

Let's assume following response JSON payload (which is from Claim Processing Fraud REST Demo):

{
  "claimId": "0",
  "fraudType": "Unspecific",
  "riskScore": "0",
  "assignedGroupId": "FD51",
  "reportId": "US0000",
  "dueDate": "2023-09-03"
}

You can use following code to update/add/delete JSON nodes:

using HP.SV.CSharp;
using System.Text;
using System;
using Newtonsoft.Json.Linq;

namespace HP.SV
{
    public class CSharpRule
    {
        public static void Execute(HpsvRootObject sv) {
            byte[] binaryData = Convert.FromBase64String(sv.Response.BinaryContent.Data);
            string stringData = Encoding.UTF8.GetString(binaryData);
            string updatedStringData = UpdateResponse(stringData);
            binaryData = Encoding.UTF8.GetBytes(updatedStringData);
            sv.Response.BinaryContent.Data = Convert.ToBase64String(binaryData);
        }

        /// <summary>
        /// Example of parsing and updating JSON with LINQ approach using built-in Newtonsoft JSON library.
        /// 
        /// For more information see https://www.newtonsoft.com/json/help/html/queryinglinqtojson.htm
        /// </summary>
        private static string UpdateResponse(string payloadString) {
            // parse to JSON object using built-in Newtonsoft library
            JObject json = JObject.Parse(payloadString);

            // updating existing value
            json["fraudType"] = "FalsifiedIdentity";

            // inserting new node
            json["newNode"] = "new value";

            // removing existing node
            json.Remove("dueDate");

            // serialize back to string
            return json.ToString();
        }
    }
}

The result is going to be:

{
  "claimId": "0",
  "fraudType": "FalsifiedIdentity",
  "riskScore": "0",
  "assignedGroupId": "FD51",
  "reportId": "US0000",
  "newNode": "new value"
}

Labels:

How To-Best Practice
Support Tips/Knowledge Docs
Comment List
Related
Recommended