MVC4:包括以JSON对象名称 [英] MVC4: Include object name in Json

查看:78
本文介绍了MVC4:包括以JSON对象名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我一直在挣扎了一段时间MVC4(测试版)问题的问题。问题是,我想创建增加了我的WebAPI对象名称的JSON。将JSON必须创建,这是作为接收端需要这一点。我的.NET / MVC的知识有限,所以请多多包涵。我想关于这个问题的搜索,但MVC4仍处于测试阶段,很难找到关于这一问题的好消息。

I have a question on a MVC4 (beta) issue I have been struggling with for some time now. The issue is that I want to create a json with the object name added for my webapi. The json has to be created this was as the receiving side needs this. My .NET/MVC knowledge is limited so please bear with me. I tried searching on the subject, but as MVC4 is still in beta it's difficult to find good info on this subject.

我已经导入我的解决方案的JSON.NET格式化,但是这不会添加对象名称

I have already imported the JSON.NET formatter in my solution, but this does not add the Object name

这是目前在MVC4创建JSON:

The json that is now created in MVC4:

[{"ID":36,"Name":"Test3","Description":"Description Test3"},{"ID": 37,"Name": "Test4","Description": "Description Test4"}]

和我想的JSON看起来是这样的:

And I would like the json to look like this:

{"Goal":[{"ID":36,"Name":"Test3","Description":"Description Test3"},{"ID": 37,"Name": "Test4","Description": "Description Test4"}]}

所以我喜欢的对象名称(目标),以包含在JSON。

So I like the object name (Goal) to be included in the json.

在我的API控制器中的code我使用的是这样的:

The code in my api controller I am using for this is:

    StoreDBContext db = new StoreDBContext();

    //
    // GET /api/goals
    public IQueryable<Goals> Get()
    {
        return db.Goals;
    }

我想我需要遍历某处添加对象的名字,但我不知道如何...希望有人能帮助我这个!

I assume I need to loop through somewhere to add the object name, but I am not sure how... Hopefully someone can help me out with this!

推荐答案

返回是这样的:

new { Goal = db.Goals().AsEnumerable().ToList() }

您可以使用一个匿名对象添加不在对象属性和东西。

You can use an anonymous object to add properties and stuff that aren't in the object.

您也可以编写自定义转换器JSON.NET如果你想让它正确地反序列化,但如果你不关心输出的反序列化,上面的解决方案,将工作。

You can also write custom converters for JSON.NET if you want it to deserialize properly, but if you don't care about deserialization of the output, the above solution will work.

这篇关于MVC4:包括以JSON对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆