我遇到一个问题,我要从我的rest api返回一个完整的guid,但是我只想让getMessage可以动态显示,而不是对其进行硬编码。谁能帮我解决这个问题。谢谢您的帮助。
我的孩子名字在guid上方
Json:
{
"42f6be79-443b-4845-8549-865af9e74988": {
"Active": true,
"CompletedMessage": "Placeholder",
"CreatedBy": "",
"Description": "Placeholder",
"DisplayName": "Placeholder1",
"ID": "be193200-c277-48bd-90ab-796e869f2e0b",
"QuestionsIDs": [
"bd341962-6c7f-459d-88ea-86aa7186840a",
"bd341962-6c7f-459d-88ea-86aa7186840a"
],
"WelcomeMessage": "Placeholder3"
}
}
代码:
public Text welcomeMessage;
private async void welcomeMessage()
{
Dictionary<string, Questions> questionDictionary = new Dictionary<string, Questions>();
string json = @"{https://PROJECT_URL.firebaseio.com/Tests/WelcomeMessage.json";
questionDictionary = JsonConvert.DeserializeObject<Dictionary<string, Questions>>(json);
foreach (Questions question in questionDictionary.Values)
{
Guid[] guids = question.QuestionsIDs;
string welcomeMessage = question.WelcomeMessage;
welcomeMessageShown = GetComponent<Text>();
welcomeMessageShown.text = welcomeMessage.ToString();
}
答案 0 :(得分:0)
首先创建一个与您的对象匹配的类。可以说Question
public partial class Question
{
[JsonProperty("Active")]
public bool Active { get; set; }
[JsonProperty("CompletedMessage")]
public string CompletedMessage { get; set; }
[JsonProperty("CreatedBy")]
public string CreatedBy { get; set; }
[JsonProperty("Description")]
public string Description { get; set; }
[JsonProperty("DisplayName")]
public string DisplayName { get; set; }
[JsonProperty("ID")]
public Guid Id { get; set; }
[JsonProperty("QuestionsIDs")]
public Guid[] QuestionsIDs { get; set; }
[JsonProperty("WelcomeMessage")]
public string WelcomeMessage { get; set; }
}
由于我们的json是键值对,因此我们需要deserialize将其保存为字典
我们的词典定义为
Dictionary<string, Question> questionDictionary = new Dictionary<string, Question>();
现在使用Newtonsoft.Json
,我们可以将其反序列化到字典中。
string json = @"{
'42f6be79-443b-4845-8549-865af9e74988': {
'Active': true,
'CompletedMessage': 'Placeholder',
'CreatedBy': '',
'Description': 'Placeholder',
'DisplayName': 'Placeholder1',
'ID': 'be193200-c277-48bd-90ab-796e869f2e0b',
'QuestionsIDs': [
'bd341962-6c7f-459d-88ea-86aa7186840a',
'bd341962-6c7f-459d-88ea-86aa7186840a'
],
'WelcomeMessage': 'Placeholder3'
}
}";
Dictionary<string, Question> questionDictionary = JsonConvert.DeserializeObject<Dictionary<string, Question>>(json);
foreach (Question question in questionDictionary.Values)
{
Guid[] guids = question.QuestionsIDs; // Do whatever you want with it
string welcomeMessage = question.WelcomeMessage;
}