2015-01-29 2 views
1

У меня есть этот формат JSONКак отформатировать json от контроллера MVC 5 следующим образом?

[ 
    { 
    info: { 
     name: "Quiz no 1", 
     main: "this is description of quiz no 1", 
     results: "this is the result or remarks after the quiz." 
    }, 
    question: { 
     q: "1 + 1 is?", 
     a: { 
      option: "one", 
      correct: false 
     } 
    } 
}, 
{ 
    info: { 
     name: "Quiz no 1", 
     main: "this is description of quiz no 1", 
     results: "this is the result or remarks after the quiz." 
    }, 
    question: { 
     q: "1 + 1 is?", 
     a: { 
      option: "two", 
      correct: true 
     } 
    } 
}, 
{ 
    info: { 
     name: "Quiz no 1", 
     main: "this is description of quiz no 1", 
     results: "this is the result or remarks after the quiz." 
    }, 
    question: { 
     q: "1 + 1 is?", 
     a: { 
      option: "three", 
      correct: false 
     } 
    } 
}, 
{ 
    info: { 
     name: "Quiz no 1", 
     main: "this is description of quiz no 1", 
     results: "this is the result or remarks after the quiz." 
    }, 
    question: { 
     q: "1 + 1 is?", 
     a: { 
      option: "four", 
      correct: false 
     } 
    } 
} 
] 

это JsonResult от моего контроллера здесь есть код, который я использовал

public JsonResult GetData() 
    { 
     var quizJSON = from a in db.infoQuestions 
         join b in db.QuestionAnswers1 
         on a.questionAnswerID equals b.questionAnswerID 
         select new 
         { 
          info = new 
          { 
           name = a.info.name, 
           main = a.info.main, 
           results = a.info.result 
          }, 
          question = new 
          { 
           q = b.Question.question1, 
           a = new 
           { 
            option = b.Answer.option, 
            correct = b.Answer.correct 
           } 
          } 
         }; 
     return Json(quizJSON, JsonRequestBehavior.AllowGet); 
    } 

проблема формат JSON, мне нужно что-то вроде этого

"info": { 
    "name": "Test Your Knowledge!!", 
    "main": "<p>Think you're smart enough to be on Jeopardy? Find out with this super crazy knowledge quiz!</p>", 
    "results": "<h5>Learn More</h5><p>Etiam scelerisque, nunc ac egestas consequat, odio nibh euismod nulla, eget auctor orci nibh vel nisi. Aliquam erat volutpat. Mauris vel neque sit amet nunc gravida congue sed sit amet purus.</p>" 
}, 
"questions": [ 
    { 
     "q": "What number is the letter A in the English alphabet?", 
     "a": [ 
      {"option": "8",  "correct": false}, 
      {"option": "14",  "correct": false}, 
      {"option": "1",  "correct": true}, 
      {"option": "23",  "correct": false} 
     ] 
    }, 
    { 
     "q": "Which of the following best represents your preferred breakfast?", 
     "a": [ 
      {"option": "Bacon and eggs",    "correct": false}, 
      {"option": "Fruit, oatmeal, and yogurt", "correct": true}, 
      {"option": "Leftover pizza",    "correct": false}, 
      {"option": "Eggs, fruit, toast, and milk", "correct": true} 
     ] 
    }, 
    { 
     "q": "Where are you right now? Select ALL that apply.", 
     "a": [ 
      {"option": "Planet Earth",   "correct": true}, 
      {"option": "Pluto",     "correct": false}, 
      {"option": "At a computing device", "correct": true}, 
      {"option": "The Milky Way",   "correct": true} 
     ] 
    }, 
    { 
     "q": "How many inches of rain does Michigan get on average per year?", 
     "a": [ 
      {"option": "149", "correct": false}, 
      {"option": "32",  "correct": true}, 
      {"option": "3",  "correct": false}, 
      {"option": "1291", "correct": false} 
     ] 
    }, 
    { 
     "q": "Is Earth bigger than a basketball?", 
     "a": [ 
      {"option": "Yes", "correct": true}, 
      {"option": "No",  "correct": false} 
     ] 
    } 
] 

Могу ли я сгенерировать его с помощью контроллера, или я должен получить данные по частям и объединить их. Какое лучшее решение для моей проблемы. Заранее спасибо сэр и мэм

+0

использовать класс ViewModel –

+0

Спасибо @EhsanSajjad, но как? –

ответ

0

Создать модель представления со следующей структурой:

public class Info 
{ 
    public string name { get; set; } 
    public string main { get; set; } 
    public string results { get; set; } 
} 

public class A 
{ 
    public string option { get; set; } 
    public bool correct { get; set; } 
} 

public class Question 
{ 
    public string q { get; set; } 
    public List<A> a { get; set; } 
} 

public class RootObject 
{ 
    public Info info { get; set; } 
    public List<Question> questions { get; set; } 
} 

Переименовывать классы, как вы считаете нужным. Я использую инструмент для создания кода json2csharp.

Ваш контроллер код действия станет:

public JsonResult GetData() 
    { 
     var quizJSON = from a in db.infoQuestions 
         join b in db.QuestionAnswers1 
         on a.questionAnswerID equals b.questionAnswerID 
         select new 
         { 
          info = new Info 
          { 
           name = a.info.name, 
           main = a.info.main, 
           results = a.info.result 
          }, 
          questions = new List<Question>() { new Question 
          { 
           q = b.Question.question1, 
           a = new List<A>() { new A 
           { 
            option = b.Answer.option, 
            correct = b.Answer.correct 
           } 
           } 
          } 
          } 
         }; 
     return Json(quizJSON, JsonRequestBehavior.AllowGet); 
    } 
+0

спасибо за ваш быстрый реагировать, но JsonResult еще не тот же формат, что мне нужно –

+0

'[ { информация: { название:«Тест № 1», главная:«это описание викторины № 1», результаты: «это результат или замечания после викторины». }, вопросы: [ { д: "1 + 1", а: [ { вариант: "один", правильно: ложные } ] } ] }] ' –

+0

можно перечислить весь вопрос под информацией и всем ответом по вопросу, подобному тому, который я дал –