如何在c#中返回指定的Json格式

时间:2016-06-03 04:46:34

标签: c# angularjs json

大家好我正在尝试使用angular JS构建一个测验应用程序,我有两个表问题和答案,代码如下

public class Question
{
    public int QuestionID { get; set; }
    public string QuestionName { get; set; }
    public List<Options> Options = new List<Options>();
}

public class Options
{
    public int AnswerId { get; set; }
    public int QuestionID { get; set; }
    public string Answer { get; set; }
    public bool isAnswer { get; set; }
}

public static class QuizDetails
{
    public static string GetQuiz()
    {
        Dictionary<int, List<Question>> displayQuestion = new Dictionary<int, List<Question>>();

        //List<Quiz> quiz = new List<Quiz>();
        //Options op1 = new Options();

        dbDataContext db = new dbDataContext();
        var v = (from op in db.QUESTIONs
                 join pg in db.ANSWERs on op.QUESTION_ID equals pg.QUESTION_ID
                 select new { Id = op.QUESTION_ID, Name = op.QUESTION_NAME, pg.ANSWER_ID, pg.QUESTION_ID, pg.ANSWER_DESCRIPTION, pg.CORRECT_ANSWER }).ToList();
        return JsonConvert.SerializeObject(v);
    }
}

这是我构建应用程序的参考代码 http://www.codeproject.com/Articles/860024/Quiz-Application-in-AngularJs,如何根据JS文件中编写的代码返回JSON格式可以帮助我

1 个答案:

答案 0 :(得分:1)

现在GetQuiz返回表示对象的字符串。您的客户端并不真正知道字符串包含什么,它只是将其作为普通字符串处理。

您可以以其他方式返回,例如:

return new HttpResponseMessage
            {
                Content = new StringContent(
                    JsonConvert.SerializeObject(v),
                    System.Text.Encoding.UTF8,
                    "application/json")
            };

如果您想继续将其作为字符串返回,则必须在客户端中手动反序列化它:

var object = angular.fromJson(returnedData);