C#MVC4 Web API-结果JSON应该返回对象而不是$ ref到对象 [英] C# MVC4 Web API - Resulting JSON should return objects instead of $ref to object

查看:66
本文介绍了C#MVC4 Web API-结果JSON应该返回对象而不是$ ref到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用EntityFramework for ORM的ASP.NET MVC 4 Web API应用.

I have an ASP.NET MVC 4 Web API app using EntityFramework for ORM.

在我返回的JSON中,在某些情况下,多个父节点存在相同的子节点.在这些情况下,子节点的第一次出现在其所有成员中都是完全可见的.任何后续出现都将显示为第一个出现的$ ref. 相反,我希望每次在返回的JSON中显示完整对象时就看到它.

In the JSON I return, there are some cases where the same child node is present for multiple parent nodes. In these cases, the first occurrence of the child node is fully visible with all it's members. Any subsequent occurrence shows up as a $ref to the first occurrence. I'd like instead to see the full object everytime it shows up in the JSON returned.

例如,没有看到:

    [{
    "$id": "1",
    "userId": 1,
    "Badge": {
        "$id": "2",
        "badgeId": 1,
        "badgeName": "Gold"
        }
    }, {
    "$id": "3",
    "userId": 2,
    "Badge": {
        "$ref": "2"
        }
    }]

我想看看:

    [{
    "$id": "1",
    "userId": 1,
    "Badge": {
        "$id": "2",
        "badgeId": 1,
        "badgeName": "Gold"
        }
    }, {
    "$id": "3",
    "userId": 2,
    "Badge": {
        "$id": "4",
        "badgeId": 1,
        "badgeName": "Gold"
        }
    }]

基本上,我想摆脱JSON中的所有"$ ref".有办法吗?

Basically I want to get rid of any "$ref" in the JSON. Is there a way?

谢谢!

推荐答案

一种简单的方法是编辑生成的实体类代码.对于每个实体类,将分配一个[DataContract(IsReference=true)]属性.

An easy way is to edit the generated entity classes code. For each of the entity classes, there will be a [DataContract(IsReference=true)] attribute assigned.

类似以下内容:

[EdmEntityTypeAttribute(NamespaceName="YourNamespace", Name="YourEntity")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class YourEntity : EntityObject
{

将其更改为IsReference=false.那应该可以解决问题.

Change it to IsReference=false. That should do the trick.

这篇关于C#MVC4 Web API-结果JSON应该返回对象而不是$ ref到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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