简体   繁体   English

使用WebAPI C#创建嵌套的JSON?

[英]Create nested JSON with WebAPI C#?

I need to create a nested JSON for a Trivia application using WebAPI. 我需要使用WebAPI为Trivia应用程序创建嵌套的JSON。 My Database structure is 我的数据库结构是

TriviaQuiz - A Quiz can have many questions. TriviaQuiz-测验可以有很多问题。 TriviaQuestion - A Question can have many options (choices) TriviaOption - List of answers (choices) TriviaQuestion-一个问题可以有很多选项(选择)TriviaOption-答案列表(选择)

I need to Produce JSON in below Format 我需要以以下格式产生JSON

{
    "quiz" : [{
        "id" : 1,
        "name" :"Guess Fruit Color",
        "description": "You need to guess color of fruits",
        "questions" : [
            {"id" : 1000 , "quizId" : 1 , "description": "The color of apple is" , "options" : [
                          {"id" : 1 , "questionId" : 1000 , "description" : "Green", "correctAnswer" : false },
                          {"id" : 2 , "questionId" : 1000 , "description" : "Red",   "correctAnswer" : true },
                          {"id" : 3 , "questionId" : 1000 , "description" : "Pink",  "correctAnswer" : false },
                          {"id" : 4 , "questionId" : 1000 , "description" : "Purple", "correctAnswer": false }      
            ]
            },
            {"id" : 1001 , "quizId" : 1 , "description": "The color of mangoss is" , "options" : [
                          {"id" : 5 , "questionId" : 1001 , "description" : "Green", "correctAnswer" : false },
                          {"id" : 6 , "questionId" : 1001 , "description" : "Red",   "correctAnswer" : false },
                          {"id" : 6 , "questionId" : 1001 , "description" : "Yello", "correctAnswer" : true },
                          {"id" : 8 , "questionId" : 1001 , "description" : "Purple", "correctAnswer": false }      
            ]
            }      
        ]}
    ]
}

I have designed my class like 我的班级设计得像

public class TriviaQuiz
    {
        public int id { get; set; }
        public string name { get; set; }
        public string description { get; set; }

        //A Quiz can have many questions
        public virtual List<TriviaQuestion> questions { get; set; }
    }

public class TriviaQuestion
    {
        [Key(), ForeignKey("triviaQuiz")]
        public int id { get; set; }
        public string description { get; set; }

        //Navigation Property to set foreign key relationship
        [JsonIgnore]
        public virtual TriviaQuiz triviaQuiz { get; set; }

       //A question can have many options 
        public virtual List<TriviaOption> options { get; set; }
    }

public class TriviaOption
    {
        public int id { get; set; }
        [ForeignKey("triviaQuestion")]
        //Tell EF That questionId is a Foreign key to TriviaQuestion table
        public int questionId { get; set; }
        public string description { get; set; }
        public Boolean correctAnswer { get; set; }

        //Navigation Property to set up Foreign key relation ship
        [JsonIgnore]
        public virtual TriviaQuestion triviaQuestion { get; set; }
    }

My WebAPI Looks like this 我的WebAPI看起来像这样

public List<TriviaQuiz> getTopJson()
        {
            return _db.TriviaQuizs.ToList();
        }

Can some some suggest what is the best approach to generate JSON. 有人可以建议什么是生成JSON的最佳方法。 Should I be creating a ViewModel for this? 我应该为此创建一个ViewModel吗?

When I run this I get an error: One or more validation errors were detected during model generation: 运行此命令时出现错误:模型生成期间检测到一个或多个验证错误:

TriviaQuestion_triviaQuiz_Source: : Multiplicity is not valid in Role 'TriviaQuestion_triviaQuiz_Source' in relationship 'TriviaQuestion_triviaQuiz'. TriviaQuestion_triviaQuiz_Source:多重性在关系“ TriviaQuestion_triviaQuiz”中的角色“ TriviaQuestion_triviaQuiz_Source”中无效。 Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be ' enter code here 1'. 由于从属角色是指关键属性,因此从属角色的多重性上限必须为“ enter code here 1”。

I have already spend a week researching but not able to find anything relevant on the internet, Can some one help. 我已经花了一个星期的时间进行研究,但无法在互联网上找到任何相关内容,能帮上忙吗?

Can some some suggest what is the best approach to generate JSON. 有人可以建议什么是生成JSON的最佳方法。 Should I be creating a ViewModel for this? 我应该为此创建一个ViewModel吗?

Nope just configure you web application to return json by default and return the object. Nope只是将您的Web应用程序配置为默认情况下返回json并返回该对象。

add

    /// <summary>
    /// The Web api config.
    /// </summary>
    public class WebApiConfig
    {
        /// <summary>
        /// Registers the specified configuration.
        /// </summary>
        /// <param name="config">The configuration.</param>
        public static void Register(HttpConfiguration config)
        {
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

            var settings = config.Formatters.JsonFormatter.SerializerSettings;

            settings.Formatting = Formatting.None;
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
            settings.DateParseHandling = DateParseHandling.DateTimeOffset;
            settings.Converters.Add(new OptionalJsonConverter());

to your app_start folder 到您的app_start文件夹

When I run this I get an error: One or more validation errors were detected during model generation: 运行此命令时出现错误:模型生成期间检测到一个或多个验证错误:

your using an ORM, I'm guessing from the message. 您正在使用ORM,我从消息中猜测出来。 You have a many-to-one defined but neither side owns the relationship. 您已定义了多对一关系,但没有一方拥有该关系。 try adding public intTriviaQuiz triviaQuizId { get; set; } 尝试添加public intTriviaQuiz triviaQuizId { get; set; } public intTriviaQuiz triviaQuizId { get; set; }

As a general observation it looks like your using the same model for both the database and the api. 作为一般观察,您似乎对数据库和api使用相同的模型。 I wouldn't advice this. 我不会建议这个。 Rather create models dedicated to the database and ones dedicated to the api (DTO's). 而是创建专用于数据库的模型和专用于api的模型(DTO)。 Then map between them this may be a 1-1 mapping at present but will save you potential headaches in the long run. 然后在它们之间进行映射,当前可能是1-1映射,但从长远来看可以节省您的头痛。

If the only purpose of this application is to provide the data, and not any presentation layer; 如果此应用程序的唯一目的是提供数据,而不提供任何表示层; you don't need to code a view model. 您不需要编写视图模型的代码。 It's also generally bad practice to use database layer attributes (Key, ForeignKey etc..) on the objects that you're serializing - you probably want a safer customized serializable version of the objects that you retrieved from database. 在要序列化的对象上使用数据库层属性(Key,ForeignKey等)通常也是一种不好的做法-您可能需要从数据库中检索到的对象的更安全的自定义可序列化版本。 For now just remove 现在就删除

[Key(), ForeignKey("triviaQuiz")]

and

[ForeignKey("triviaQuestion")]

from the objects, you can include Newtonsoft.JSon library to your project, and then just call 从对象中,您可以将Newtonsoft.JSon库包含到您的项目中,然后只需调用

JsonConvert.SerializeObject(_db.TriviaQuizs.ToList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM