[英]How to get $context variables from the Watson Conversation Service in Unity?
我正在嘗試獲取在Unity項目中的Watson對話對話框中創建的上下文變量。 我能夠使整個JSON對話框顯示在Unity中,並從json文件中獲取意圖,實體和輸出文本。 因此,我沒有從json文件中獲取輸出:{text [],而是嘗試從JSON文件中獲取context:{variable:value,但我無法理解。
這是歡迎對話框節點的JSON文件,我想在其中讀取destination_city變量以將其設置為等於Unity變量/字符串。
{
"context": {
"date": null,
"time": null,
"hotel": null,
"DateEnd": null,
"DateBegin": null,
"PeriodDate": null,
"numberKids": null,
"roomsHotel": null,
"PeriodNumber": null,
"numberAdults": 0,
"departure_city": null,
"transportation": null,
"destination_city": "London",
"kidDiscountRepeat": null
},
"output": {
"text": {
"values": [
"Hello, this is the Watson Travel agency."
],
"selection_policy": "sequential"
}
}
}
這是我在Unity中獲得沃森對話的響應並顯示該對話框節點的整個JSON文件的代碼的一部分:
void HandleMessageCallback (object resp, Dictionary customData)
{ object _tempContext = null; (resp as Dictionary ).TryGetValue("context", out _tempContext);
if (_tempContext != null)
conversationContext = _tempContext as Dictionary<string, object>;
Dictionary<string, object> dict = Json.Deserialize(customData["json"].ToString()) as Dictionary<string, object>;
// load output --> text;answer from Json node
Dictionary <string, object> output = dict["output"] as Dictionary<string, object>;
List<object> text = output["text"] as List<object>;
string answer = text[0].ToString();
Debug.Log("WATSON | Conversation output: \n" + answer);
//======== Load $ context variable attempts =============================
Debug.Log("JSON INFO: " + customData["json"].ToString());
//=====================================
if (conversationOutputField != null)
{
conversationOutputField.text = answer;
}
使用當前的代碼,您應該能夠使用
var context = dict["context"] as Dictionary<string, object>
現在您有了上下文,您可以以相同的方式訪問它的內容
var mycity = context["destination_city"]
即使這樣做確實可行,但如果您要設置一個解決方案來操縱/訪問Json,我強烈建議您建立數據模型以進行序列化來回傳輸 ,為此,請查看Unity的JsonUtility (Json序列化)
讓我們以Unity手冊為例:
首先,我們創建所需的Json信息的Model
類,在這種情況下,我們需要有關播放器的信息,為此,我們創建3個字段,即int level
, float timeElapsed
和string playerName
。
[Serializable]
public class MyClass
{
public int level;
public float timeElapsed;
public string playerName;
}
在這里,我們為類MyClass
創建了一個名為myObject
的新實例,並手動設置了它的字段值(實際上,如何設置值在這里並不重要)
MyClass myObject = new MyClass();
myObject.level = 1;
myObject.timeElapsed = 47.5f;
myObject.playerName = "Dr Charles Francis";
要序列化myObject
只需將其作為參數傳遞給JsonUtility
的.ToJson
方法。
string json = JsonUtility.ToJson(myObject);
現在,我們將類的對象等效為Json字符串:
{"level":1,"timeElapsed":47.5,"playerName":"Dr Charles Francis"}
如果要用來自Json的數據填充C#對象,可以通過調用JsonUtility
的.FromJson<TypeOfTheClassImMappingTo>
方法並將其json字符串作為參數傳遞來實現。
myObject = JsonUtility.FromJson<MyClass>(json);
這些只是基本操作,是您可以使用JsonUtility的Class / Json序列化做的表面工作
該解決方案更具可維護性。 您可以擴展它以使用任何數量的模型類型,並具有C#對象導航的優點和便利性。 這對於創建將使用您的數據對象的系統特別有趣。
如果您對Json Utility有疑問,例如如何管理數組,嵌套數據等。我強烈建議您花幾分鍾閱讀@Programmers,了解有關JsonUtility實踐的答案 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.