解析 unity WWW api 对模型的响应

parse unity WWW api response to model

如何将我的网络api 响应解析为有用的模型?

这是我的 api 电话:

  IEnumerator GetQuestion(){
    string input = new QuestionThemeRequest(){ QuestionTheme = "BAJS" }.ToString();
    Hashtable headers = new Hashtable();
    headers.Add("Content-Type", "application/json");
    byte[] body = Encoding.UTF8.GetBytes (input);
    WWW www = new WWW ("http://localhost:52603/api/Question/GetRandomQuestionByTheme", body, headers);
    yield return www;
}

这里

   public class Question{
    public int Id { get; set; }
    public string Answere { get; set; }
}

我试过这样的事情:

Question q = new Question();
q = GetQuestion();

但这似乎不起作用。

您提供的代码不会 运行,因为您正试图将其称为无效。但它是一个协程(IEnumerator)。为了正确 运行 你需要启动协程,可以按以下方式完成

StartCoroutine(GetQuestion());

StartCoroutine("GetQuestion");

请记住,从 unity 5.0 开始,第二个选项将不再可用

有关协程的更多信息,您应该查看 unity docs

它基于您的服务器响应的内容。

如果是 JSON 你可以用 SimpleJSON 来解析它。

@MX D 解决你的延迟问题

这是示例代码,但不要忘记我假设您的 www.text 是 JSON 类型。

using SimpleJSON;

IEnumerator GetQuestion(){
    string input = new QuestionThemeRequest(){ QuestionTheme = "BAJS" }.ToString();
    Hashtable headers = new Hashtable();
    headers.Add("Content-Type", "application/json");
    byte[] body = Encoding.UTF8.GetBytes (input);
    WWW www = new WWW ("http://localhost:52603/api/Question/GetRandomQuestionByTheme", body, headers);
    yield return www;
    if((!string.IsNullOrEmpty(www.error))) {
       print( "Error downloading: " + www.error );
    } else {
       JSONNode questionJSON = JSONNode.Parse (www.text);
       Question q = new Question();
       q.Id = questionJSON["id"];
       q.Answere = questionJSON["Answere"];
    }
}

更好的解决方案是

using SimpleJSON;

public YourClass : MonoBehaviour{
    public delegate void WWWCalback(WWW wwwData);
    private void answersCallback(WWW wwwData){
        JSONNode questionJSON = JSONNode.Parse (wwwData.text);
        Question q = new Question();
        q.Id = questionJSON["id"];
        q.Answere = questionJSON["Answere"];
    }
    private void getAnswers(){
      StartCoroutine(GetQuestion(answersCallback));
    }
    IEnumerator GetQuestion(WWWCalback callback){
      string input = new QuestionThemeRequest(){ QuestionTheme = "BAJS" }.ToString();
      Hashtable headers = new Hashtable();
      headers.Add("Content-Type", "application/json");
      byte[] body = Encoding.UTF8.GetBytes (input);
      WWW www = new WWW ("http://localhost:52603/api/Question/GetRandomQuestionByTheme", body, headers);
      yield return www;
      if((!string.IsNullOrEmpty(www.error))) {
            print( "Error downloading: " + www.error );
      } else {
            callback(www);
      }
    }
}

就像那样。可能会出现一些语法或其他问题。我不查。