gpt4 book ai didi

c# - 如何从数据库创建嵌套的 json?

转载 作者:行者123 更新时间:2023-11-30 22:55:03 25 4
gpt4 key购买 nike

我创建了一个 web api,它以 json 格式显示数据库中表中的数据。我想创建一个嵌套的 api。

我该怎么做?

我调用 api 时的 json:

{
"ID":1,
"plVersion":1,
"mID":10,
"sID":1025,
"orID":null,
"x":22.9935,
"y":40.5885
}

我想要这样的东西

[
{
"ID":1,
"header":{
"plVersion":1,
"mID":10,
"sID":1025
},
"mContainer":{
"aID":{
"orID":null
},
"Position":{
"x":22.9935,
"y":40.5885
}
}
}
]

我的testController.cs

public class testController : ApiController
{
[Route("api/test")]
public IEnumerable<test> Get()
{
using (Raw_DataEntities entities = new Raw_DataEntities())
{
return entities.tests.ToList();
}
}

[Route("api/test/{id}")]
public test Get(int id)
{
using (Raw_DataEntities entities = new Raw_DataEntities())
{
return entities.tests.FirstOrDefault(e => e.ID == id);
}
}
}

最佳答案

您可以构建一个映射到您想要的 json 结构的包装器类,填充它并返回包装器而不是 Controller 中的实体。你的包装看起来像这样:

public class Header
{
public int plVersion { get; set; }
public int mID { get; set; }
public int sID { get; set; }
}

public class AID
{
public object orID { get; set; }
}

public class Position
{
public double x { get; set; }
public double y { get; set; }
}

public class MContainer
{
public AID aID { get; set; }
public Position Position { get; set; }
}

public class RootObject
{
public int ID { get; set; }
public Header header { get; set; }
public MContainer mContainer { get; set; }
}

为了能够轻松地为给定的 json 创建匹配的类结构,您可以使用像 json2csharp 这样的工具。 .

映射数据并返回:

[Route("api/test/{id}")]
public test Get(int id)
{
using (Raw_DataEntities entities = new Raw_DataEntities())
{
var entity = entities.tests.FirstOrDefault(e => e.ID == id);
}

var root = new RootObject();
// Filling the object
root.ID = entity.Id;
// etc. ...

return root;
}

为了拥有更简洁的操作方法,我建议编写一个扩展方法来将实体映射到它的包装对象:

public static class EntityExtensions
{
public static RootObject ToJsonWrapper(this Entity entity)
{
if (entity == null)
return null;

var root = new RootObject();
root.ID = entity.Id;
// etc ...
}
}

然后像这样在 Action 中调用它:

[Route("api/test/{id}")]
public test Get(int id)
{
using (Raw_DataEntities entities = new Raw_DataEntities())
{
return entities.tests.FirstOrDefault(e => e.ID == id).ToJsonWrapper();
}
}

关于c# - 如何从数据库创建嵌套的 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55685221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com