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);
}
}
}
}
CodePudding user response:
Disclaimer I'm not familiar with the peculiarities of Unity
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.
UPDATE - Using A Model Class
If, for whatever reason, you need/have a model class instead of an anonymous type, you should instantiate that with the necessary values and pass that to the serializer...
Given the model classes MyModel
and MyModelValues
using System;
[Serializable]
public class MyModel
{
[SerializeField]
public MyModelValues values;
}
[Serializable]
public class MyModelValues
{
[SerializeField]
public string AppName;
[SerializeField]
public string Time;
}
Then you can substitute the creation of model
using the model classes.
// create our model as an anonymous type using the `appName` variable value.
var model = new MyModel
{
values = new MyModelValues
{
AppName = appName,
Time = "23:15"
}
};