unity json文件解析大模型返回结果
using UnityEngine;
using UnityEngine.UI;
using System;
public class DisplayJsonContent : MonoBehaviour
{
// 引用UI Text组件
public Text displayText;
// JSON字符串(从模型返回的内容)
private string jsonString = "{\"choices\":[{\"message\":{\"content\":\"首先,我们需要了解一些关于曼陀罗艺术的基本知识。\",\"role\":\"assistant\"},\"finish_reason\":\"stop\",\"index\":0,\"logprobs\":null}],\"object\":\"chat.completion\",\"usage\":{\"prompt_tokens\":739,\"completion_tokens\":330,\"total_tokens\":1069},\"created\":1736990602,\"system_fingerprint\":null,\"model\":\"qwen-vl-plus\",\"id\":\"chatcmpl-d2279ac6-e636-90cb-a15e-41330726e719\"}";
void Start()
{
// 解析JSON并显示内容
ParseAndDisplayJson(jsonString);
}
// 解析JSON并显示内容
void ParseAndDisplayJson(string jsonString)
{
try
{
// 解析JSON
var parsedJson = JsonUtility.FromJson<ChatCompletion>(jsonString);
// 提取message内容
string messageContent = parsedJson.choices[0].message.content;
// 显示在Text组件中
displayText.text = messageContent;
}
catch (Exception ex)
{
Debug.LogError("解析JSON时出错: " + ex.Message);
}
}
// 定义用于解析JSON的类
[System.Serializable]
public class ChatCompletion
{
public Choice[] choices;
}
[System.Serializable]
public class Choice
{
public Message message;
}
[System.Serializable]
public class Message
{
public string content;
}
}