简体   繁体   English

如何将以点表示法格式化的json属性转换为ac#类

[英]How to convert json properties that are formatted in dot notation to a c# class

I am using HttpClient to retrieve data from an api. 我正在使用HttpClient从api检索数据。 Unfortunately, I don't have control over the property names, they were all written in dot notation, for example 不幸的是,我无法控制属性名称,例如,它们全都以点表示法编写

"staff":[{"responsible.user":"Y","staff.type":
    {"staff.type.mnemonic":"C","staff.type.name":"Consultant"}]

There is probably at least 100 or so properties in this json callback that are like this. 这个json回调中可能至少有100个左右这样的属性。 I need to return back a json object that removes the dots (ie change responsible.user to responsibleuser ) Is there a way to map ac# class and return the format I want back? 我需要返回一个删除点的json对象(即,将responsible.user人。 responsibleuser更改为responsibleuser ),有没有办法映射ac#类并返回我想要的格式?

I have ac# class using the [DataContract] attribute and [Datamember(Name=)] fields to map the values, but when I look at the json that is returned, they still have the dots in the properties. 我有一个使用[DataContract]属性和[Datamember(Name=)]字段来映射值的ac#类,但是当我查看返回的json时,它们在属性中仍然带有点。

This is what I started to work with in my controller 这就是我开始在控制器中使用的功能

 using(HttpClient c = new HttpClient())
        {
            c.DefaultRequestHeaders.Authorization =
               new System.Net.Http.Headers.AuthenticationHeaderValue(
                   "Bearer",
                   "Cazqmx-TTHOOfnJy92SRng=="
               );
            var link = string.Format(AmsApiGet, "6894998", "TYEE");
            var res = await c.GetStringAsync(link);
            TaskAPI task = new TaskAPI();

            task = JsonConvert.DeserializeObject<TaskAPI>(res);

            return Ok(task);

Basically, I am just trying to convert the property names, so that I can use typescript models in my frontend Angular side 基本上,我只是试图转换属性名称,以便可以在前端Angular端使用打字稿模型。

You can control the property names received by the front end by transforming the data into your own POCO (Plain Ol' C# Object) before converting it to JSON. 您可以通过将数据转换为自己的POCO(Plain Ol'C#对象),然后再将其转换为JSON,来控制前端接收的属性名称。

TaskAPI task = new TaskAPI();

List<myPOCO> list = new List<myPOCO>();

foreach (var item in res)
  list.Add(new myPOCO(item)); //all your mapping is in the POCO Constructor

task = JsonConvert.DeserializeObject(list); //or whatever syntax it would be

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

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