Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Provide value to JSON's attribute

I have a JSON structure inside my code, I would like to pass a value to one of the attributes. Problem is I do not know how to do this? Since it is one whole string in C#, what is the possible way to achieve this?

For example, I want to pass the string appName to the JSON’s AppName. How do I do this?

IEnumerator Start(){
  var appName = "Testing001";

  var json = @"{
        'values': {
        'AppName': '',
        'Time': '23:15',
        }
            }";

        var jsonBytes = Encoding.UTF8.GetBytes (json);

        using (var www = new UnityWebRequest (url, "POST")) {
            www.uploadHandler = new UploadHandlerRaw (jsonBytes);
            www.downloadHandler = new DownloadHandlerBuffer ();
            www.SetRequestHeader ("Content-Type", "application/json");
            www.SetRequestHeader ("Accept", "text/plain");

            yield return www.SendWebRequest ();

            if (www.isNetworkError || www.isHttpError) {
                Debug.Log (www.error);
            } else {
                Debug.Log (www.downloadHandler.text);
                Debug.Log (www.error);
            }
        }

    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

So you want to create some JSON using variable values do you?

As others (and myself) have said in the comments, you should never create JSON manually as it is so easy to make a small mistake and end up with invalid JSON.

You will either want to use rigid model classes, or in a pinch, an anonymous type.

var appName = "Testing001";

// create our model as an anonymous type using the `appName` variable value.
var model = new {
    values = new {
        AppName = appName,
        Time = "23:15"
    }
};

// Generate valid JSON
var json = JsonSerializer.Serialize(model);

The resulting, valid, JSON is

{"values":{"AppName":"Testing001","Time":"23:15"}}

As you see, property names and strings have double quotes and AppName has the desired value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading