简体   繁体   English

将模式附加到从控制器返回的Json数据

[英]Append Schema to Json data returned from controller

I am trying to add schema to JSON that is returned from every controller and every endpoint inside it. 我试图将架构添加到从每个控制器及其内部的每个端点返回的JSON。

Let's say I have an endpoint "localhost/values/get", and it returns a JSON as below. 假设我有一个端点“ localhost / values / get”,并且它返回如下的JSON。

{
    Filed1:'Field1Value',
    Field2:'Field2Value',
    Field3:3
}

I want to convert it to as follows 我想将其转换为如下

{
    Schema:[{
        Field:'Filed1',
        DataType:'String'
    },
    {
        Field:'Field2',
        dataType:'String'
    },
    {
        Field:'Field3',
        DataType:'int'
    }],
    Data:{
        Filed1:'Field1Value',
        Field2:'Field2Value',
        Field3:3
    }
}

Is there a way to add this for every return object at one place instead of doing it for every controller? 有没有一种方法可以在一个位置为每个返回对象添加此对象,而不是为每个控制器都添加呢?

something like the attributes does. 像属性一样。

I have tried the WriteResponseBodyAsync using 我已经尝试使用WriteResponseBodyAsync

Options.OutputFormatters.Insert(0, new OutputFormatter());

in the startup.cs , but I was unable to get the properties of the type that I am sending in the response. startup.cs中 ,但是我无法获取响应中发送的类型的属性。 Can someone please help me with this. 有人可以帮我吗

This is how I achieved the output formatting in my Web API. 这就是我在Web API中实现输出格式的方式。

My Startup.cs looks like below. 我的Startup.cs如下所示。 Inside the ConfigureServices 在ConfigureServices内部

services.AddMvc(Options =>
{
    Options.OutputFormatters.Insert(0, new OutputFormatter());
});

Create an OutputFormatter.cs class as follows. 如下创建一个OutputFormatter.cs类。

public OutputFormatter()
{
    SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json"));
    SupportedEncodings.Add(Encoding.GetEncoding("iso-8859-1"));
}

public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
    var response = context.HttpContext.Response;
    var responseData = Encoding.UTF8.GetBytes(LoadSchema(context));
    return response.Body.WriteAsync(responseData, 0, responseData.Length);
}

private string LoadSchema(OutputFormatterWriteContext context)
{
    var schema = new List<SchemaModel>();
    var returnData = new ReturnModel();
    foreach (var Field in (context.Object as IEnumerable<dynamic>).FirstOrDefault().GetType().GetProperties())
    {
        schema.Add(new SchemaModel
        {
            FieldName = Field.Name,
            DataType = Field.PropertyType.Name
        });
    }
    returnData.Schema = schema;
    returnData.ReturnData = context.Object;
    return JsonConvert.SerializeObject(returnData);
}

You can make changes to the way the schema is generated by changing the logic in the above code. 您可以通过更改上述代码中的逻辑来更改生成模式的方式。 Write all your controllers as is, and return the model and this OutputFormatter will take care of adding the schema to the JSON. 照原样编写所有控制器,然后返回模型,此OutputFormatter将负责将架构添加到JSON。

The JSON data would look like below. JSON数据如下所示。

{
    "Schema": [
        {
            "FieldName": "FirstProp",
            "DataType": "String"
        },
        {
            "FieldName": "SecondProp",
            "DataType": "Int32"
        },
        {
            "FieldName": "ThirdProp",
            "DataType": "Decimal"
        },
        {
            "FieldName": "FourthProp",
            "DataType": "Boolean"
        },
        {
            "FieldName": "FifithProp",
            "DataType": "DateTime"
        }
    ],
    "ReturnData": [
        {
            "FirstProp": "value0",
            "SecondProp": 0,
            "ThirdProp": -0.9,
            "FourthProp": true,
            "FifithProp": "2018-03-06T15:26:08.8428651-06:00"
        },
        {
            "FirstProp": "value1",
            "SecondProp": 1,
            "ThirdProp": 0.1,
            "FourthProp": false,
            "FifithProp": "2018-03-07T15:26:08.8428702-06:00"
        },
        {
            "FirstProp": "value2",
            "SecondProp": 2,
            "ThirdProp": 1.1,
            "FourthProp": true,
            "FifithProp": "2018-03-08T15:26:08.8428713-06:00"
        },
        {
            "FirstProp": "value3",
            "SecondProp": 3,
            "ThirdProp": 2.1,
            "FourthProp": false,
            "FifithProp": "2018-03-09T15:26:08.8428724-06:00"
        },
        {
            "FirstProp": "value4",
            "SecondProp": 4,
            "ThirdProp": 3.1,
            "FourthProp": true,
            "FifithProp": "2018-03-10T15:26:08.8428735-06:00"
        }
    ]
}

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

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