Dev guideAPI Reference
Dev guideAPI ReferenceUser GuideGitHubNuGetDev CommunitySubmit a ticketLog In
GitHubNuGetDev CommunitySubmit a ticket

OptimizelyJSON for the C# SDK

Describes the OptimizelyJSON object that the Optimizely Feature Experimentation C# SDK uses to retrieve JSON.

Since static-typed languages lack native support for JSON, the C# SDK uses the OptimizelyJson object to retrieve JSON in a flexible way.

Version

SDK v3.5 and higher

Methods

You can access JSON representations with the following methods:

MethodParametersDescription
ToStringnoneReturns a string representation of the JSON object
ToDictionarynoneReturns a dictionary representation of the JSON object: (Dictionary<string,object>)
GetValue<T>string jsonPathReturns a specified schema object (T) with the key/value pair of the JSON key you pass to this method.

If JSON key is null or empty, it populates your schema object with all JSON key/value pairs.

You can retrieve information for a nested member of the JSON data structure by using flattened JSON dot notation.
For example, if you want to access the key nestedField2 in {field1: {nestedField2: "blah"}}, you can call GetValue with the parameter "field1.nestedField2".

The OptimizelyJson object is defined as follows:

public class OptimizelyJson
{
    public string ToString();

    public Dictionary<string, object> ToDictionary();

    public T GetValue<T>(string jsonPath);
}

Examples

You can easily use OptimizelyJson, to:

  • Get a JSON string by calling the ToString method, or
  • Retrieve a specified schema from the OptimizelyJson object by calling the GetValue method.

The following example shows how to use an OptimizelyJson object to populate a schema object you declare.

//declare a schema object into which you want to unmarshal OptimizelyJson content:
public class ExampleSubObject
{
    public string? Field;
}

public class ExampleObject
{
    public int? Field1;
    public double? Field2;
    public string? Field3;
    public ExampleSubObject? Field4;
}

var datafileJsonString =
    "{\"field1\": 1, \"field2\": 2.0, \"field3\": \"3\", \"field4\": {\"field\": \"4\"}}";
var optimizelyJson =
    new OptimizelyJSON(datafileJsonString, new DefaultErrorHandler(), new DefaultLogger());

// Parse all json key/value pairs into your schema
var exampleObject = optimizelyJson.GetValue<ExampleObject>(null);

// Parse the specified key/value pair with an integer value 
int field1 = optimizelyJson.GetValue<int>("field1");

// Parse the specified key/value pair with a string value
var exampleSubObject = optimizelyJson.GetValue<ExampleSubObject>("field4.field");