Angelica cruz
Angelica cruz

Reputation: 81

Put a variable inside a string that is used as a json format

The code under is using a RestApi and is working. What I want to do is to put the variable topPlayer at the string "dani2" place. I searched in the net and the ways I found may affect the structure of string message which is necessarily that way. Can you suggest me how to put the variable topPlayer inside the string message?

public class Test2 : MonoBehaviour, IInputClickHandler
{
    [HideInInspector]
    public string topPlayer = PlayerPrefs.GetString("TopPlayer");

    public void OnInputClicked(InputClickedEventData eventData)
    {
        //UnityWebRequest request = UnityWebRequest.Post("https://hipchat.getconnected.it/v2/room/91/message", formData);
        StartCoroutine(dani());
    }

    IEnumerator dani()
    {
        //string message = "{ \"message\": \"dani2\"}";
        string message = "{ \"message\": \"topPlayer\"}";
        UnityWebRequest request = UnityWebRequest.Post("https://hipchat.getconnected.it/xxx", message);
        request.SetRequestHeader("authorization", "Bearer xxx");
        request.SetRequestHeader("content-type", "application/json");
        byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
        UploadHandlerRaw upHandler = new UploadHandlerRaw(data);
        upHandler.contentType = "application/json";
        request.uploadHandler = upHandler;

        yield return request.Send();

        if (request.isError)
        {
            Debug.Log(request.error);
        }
        else
        {
            Debug.Log("Form upload complete!");
        }
    }
}

Upvotes: 1

Views: 1144

Answers (2)

Dmitry Egorov
Dmitry Egorov

Reputation: 9650

There are several ways of injecting a variable's value into a string. The one suitable for any .NET version is using String.Format version.

However, you need to escape the variable's value before injecting it in order to avoid invalid resulting JSON like this { "message": "a"b"} (if topPlayer was a"b). System.Web.HttpUtility.JavaScriptStringEncode will help you with escaping:

string message = string.Format("{{ \"message\": \"{0}\"}}",
    System.Web.HttpUtility.JavaScriptStringEncode(topPlayer));

Please also note that outermost braces doubled ({{ ... }}). This is because single braces have special meaning for the Format function so they must be escaped by doubling.

Since C# 6.0 you also may use interpolated strings:

string message = $"{{ \"message\": \"{System.Web.HttpUtility.JavaScriptStringEncode(topPlayer))}\"}}";

Upvotes: 2

FailedUnitTest
FailedUnitTest

Reputation: 1800

Do you mean like this?

string message = string.Format("{ \"message\": \"{0}\"}",topPlayer);

Upvotes: 2

Related Questions