How can i create a nested json from database in c#?

Refresh

6 days ago

Views

9 time

0

I have created a web api which displays data from a table in database in json format.I want to create a nested api.

How can i do this ?

Thanks

My json when i call the api

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

   }

I want something like this

 [{
"ID": 1,
"header": {
    "plVersion": 1,
    "mID": 10,
    "sID": 1025
},
"mContainer": {
    "aID": {
        "orID": null

    },
    "Position": {
        "x": 22.9935,
        "y": 40.5885
    }
}
  }]

My 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);
        }
    }

}

1 answers

0

You can build a wrapper class which maps to your wanted json structure, fill it and return the wrapper instead of the entity from your controller. Your wrapper would look something like this:

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; }
}

To be able to easily create matching class structure to a given json you can use a tool like json2csharp.