locked
Returning json data format RRS feed

  • Question

  • User1295747327 posted

    Here is my code

    [HttpPost("workreportlist")]
            public IActionResult WorkReportList([FromBody] WorkReportListDto workReportListDto)
            {
                var workRpt = _repo.ReportList(workReportListDto.CompanyId);
    
                return Ok(workRpt);
            }

    Currently, i am getting like this

    [
        {
            "id": 1,
            "title": "report for 20 Jan",
            "contents": "this is contents",
           
        },
    .....

    But i want to return result like here

    {
        "status": true,
        "message": "success message",
        "code": 200,
        "result": {
            "list": [
                {
                    "id": 1,
                    "title": "report for 20 Jan",
    ......
    Tuesday, January 21, 2020 12:43 PM

All replies

  • User475983607 posted

    Very simple.  Create a C# class that matches the expected JSON format.  Unfortunately, you did not post the entire JSON object so the community cannot provide an accurate solution.  However, you can use Visual Studio to build the class yourself.

    Copy the JSON object -> Edit -> Paste Special -> Paste JSON as classes.

    Tuesday, January 21, 2020 1:05 PM
  • User1295747327 posted

    @mgebhard: Thank you for your reply.

    My JSON out put is very complicated,I do not understand, Here i am posing my entire JSON, this is what the output should be.( Assume i have all values in LIST/ARRAY)

    { 
       "status":true,
       "message":"success message",
       "code":200,
       "result":{ 
          "list":[ 
             { 
                "id":1,
                "title":"report for 20 Jan",
                "report_tasks":[ 
                   { 
                      "id":"1",
                      "title":"IOS",
                      "due_date":"2019-11-18 17:33:17",
                      "contents":"",
                      "owners_users":[ 
                         { 
                            "user_id":210,
                            "user_name":"Nick"
                         },
                         { 
                            "user_id":212,
                            "user_name":"Hong01"
                         }
                      ]
                   }
                ]
             },
             { 
                "id":9,
                "title":"Daily report",
                "report_tasks":[ 
                   { 
                      "id":"IOS",
                      "title":"IOS",
                      "due_date":"2019-11-18 17:33:17",
                      "contents":"",
                      "owners_users":[ 
                         { 
                            "user_id":210,
                            "user_name":"Nick"
                         },
                         { 
                            "user_id":212,
                            "user_name":"Hong01"
                         }
                      ]
                   },
                   { 
                      "id":"Setup",
                      "title":"Setup",
                      "due_date":"2019-11-18 17:27:14",
                      "contents":"",
                      "owners_users":[ 
                         { 
                            "user_id":210,
                            "user_name":"Nick"
                         },
                         { 
                            "user_id":212,
                            "user_name":"Hong01"
                         }
                      ]
                   }
                ]
             }
          ],
          "departments":[ 
             { 
                "id":1,
                "name":"IT"
             },
             { 
                "id":2,
                "name":"HR"
             }
          ]
       }
    }

    Wednesday, January 22, 2020 6:14 AM
  • User1535942433 posted

    Hi EngSH,

    Accroding to your codes, I suggest you could create a class of the list.Then you could read data and add data in the ReportList.

    The class just like this:

    public class list
        {
            public int id { get; set; }
            public string title { get; set; }
            public DateTime due_date { get; set; }
            public string contents { get; set; }
            public IList<owners_users> owners_user { get; set; }
            public IList<departments> department { get; set; }
        }
        public class owners_users
        {
            public int user_id { get; set; }
            public string user_name { get; set; }
        }
        public class departments
        {
            public int id { get; set; }
            public string name { get; set; }
        }

    Best regards,

    Yijing Sun

    Wednesday, January 22, 2020 8:00 AM
  • User1295747327 posted

    Hi, I got result in workRpt variable. How i can loop it and set the list class & others?

    TO keep things simple, I created below code, but still not working

     var products =  _context.Product.ToList();
                    foreach(Product p in products)
                    {
                        ProductList pl = new ProductList() // new class to represent data
                        {
                            pl.Name = p.Name,// here is error
    
    
                        }
                    }

    return Ok(ProductList );// Is this line ok?

    Wednesday, January 22, 2020 8:42 AM
  • User1120430333 posted
    var products =  _context.Product.ToList();
    ProductList pl = new ProductList() // new class to represent data
    
                    foreach(var p in products)
                    {
                        var prod = new Product();
    
                          prod.Name = p.Name;
    
                          pl.Add(prod);
                    }

    https://dzone.com/articles/different-ways-of-creating-list-of-objects-in-c

    Wednesday, January 22, 2020 5:02 PM
  • User1295747327 posted

    @DA924: this line will never work.

     pl.Add(prod);

    Does anyone can correct it?

    Tuesday, January 28, 2020 6:20 AM
  • User1120430333 posted

    This is wrong to begin with..

    ProductList pl = new ProductList() // new class to represent data

    You can't make a list like above. Where did it come from?

    It should be this.

    List<Product> pl = new List<Product>();  //this line creates  list/a collection object.

    If ProductList is a definition for a single class, then it should not be named ProductList that signifies that it's a list/collection when it is not a list/collection, which is a plural name meaning more than 1.

    var products =  _context.Product.ToList();
    List<ProductName> pl = new List<ProductName>() // new class to represent data

    foreach(var p in products)
    {
    var prodn = new ProductName();
    prodn.Name = p.Name;
    pl.Add(prod);
    }

    Now the above is technically correct, and maybe the ProductList class is named wrongly and should be something like ProductName or something..

    You should learn how to use a Linq projection using a custom type like ProductName, and you could eliminate the foreach  loop

    https://csharp-station.com/Tutorial/Linq/Lesson02

    Tuesday, January 28, 2020 8:17 AM
  • User1295747327 posted

    If you see @meg reply above, he asked like that

    Very simple.  Create a C# class that matches the expected JSON format. 

    and this code was also there in your reply. anyhow i will check

    Tuesday, January 28, 2020 8:42 AM
  • User1120430333 posted

    EngSH

    If you see @meg reply above, he asked like that

    Very simple.  Create a C# class that matches the expected JSON format. 

    and this code was also there in your reply. anyhow i will check

    Your naming convention is wrong for the class. A single class is not a multiple of anything, and the naming convention for a class should be singular. Products or Productlist is a plural naming convention meaning the list or collection has 1 or more items in the object that are enumerable.

    Tuesday, January 28, 2020 9:21 AM
  • User475983607 posted

    Your having trouble populating class properties.  Unfortunately, the community can't help much because we have no idea if your database supports the JSON structure or even has the data. 

    You need to map your data to the JSON/class structure.  This might mean creating several LINQ queries.   You can also try code first to generate the table structure that matches your JSON interface requirement.  Then you'll need to fill the tables.

    Tuesday, January 28, 2020 12:37 PM
  • User1295747327 posted

    @mgebhard: I think you understand the problem now. Let me make it very simple for 2 tables only. (tables & models fields matches)

    What i tried?

    1. I created 2 tables in database (Product & ProductImage)

         2. I created 2 classes in Model folder, below is code

    public class Product
        {
            [Key]
            public int Id { get; set; }
    
            public string Name { get; set; }
            public ICollection<ProductImage> ProductImages { get; set; }
        }
    
    [Table("ProductImages")]
        public class ProductImage
        {
            public int Id { get; set; }
    
            public string ImageName { get; set; }
            public string ImageSize { get; set; }
    
            [ForeignKey("Product")]
            public int ProductId { get; set; }
            
        }

    3. Here is my controller function to get data

     var productsWithImages = _context.Product.Where(p => p.Id == 2)
                    .Include(p => p.ProductImages).ToList();

    What i want?

    Now i want to generate & return a custom json result. Here is json format i want client side api show receive.

    { 
       "status":true,
       "message":"success message",
       "code":200,
       "result":{ 
          "list":[ 
             { 
                "Id":1,
                "ProductName":"shoes",
                "ProductImages":[ 
                   { 
                      "Id":"1",
                      "ImageName":"folder/2332.jpg"
                   },
                   { 
                      "Id":"2",
                      "ImageName":"folder/33333.jpg"
                   }
                 ]
                }
             ]
           }
         }

    I simple words, show product and its images.

    Now question is, how to generate this type of json?

    Note: please correct my code and suggest me how to do it.

    Tuesday, January 28, 2020 1:00 PM
  • User753101303 posted

    Hi,

    So it seems you want an additional C# class Root object that will have those properties including a list of products. If VS 2017 or later try https://www.c-sharpcorner.com/article/how-to-paste-json-as-classes-or-xml-as-classes-in-visual-stu/ to create automatically C# classes from your JSON sample...

    ASP.NET handles serializing the C# object returned from your web api call to json for you so that you should never need explicit deserialization/serialization code in your app.

    Edit: or if using an older VS version you could use http://json2csharp.com/, copy/paste your json sample and the "Generate" button will show matching C# classes.

    Tuesday, January 28, 2020 1:24 PM
  • User475983607 posted

    @mgebhard: I think you understand the problem now. Let me make it very simple for 2 tables only. (tables & models fields matches)

    The JSON interface does not match your entity object model.  You need to create a mapping layer between your entities and the JSON interface.

    Tuesday, January 28, 2020 2:34 PM
  • User1295747327 posted

    @PatriceSc: Thank you for your response. Ok i have generated classes from json as per your link. Now can you just show me how i will assign values to this class in my foreach loop from result?

    below is my generated classes

    public class OwnersUser
    {
        public int user_id { get; set; }
        public string user_name { get; set; }
    }
    
    public class ReportTask
    {
        public string id { get; set; }
        public string title { get; set; }
        public string due_date { get; set; }
        public string contents { get; set; }
        public List<OwnersUser> owners_users { get; set; }
    }
    
    public class List
    {
        public int id { get; set; }
        public string title { get; set; }
        public List<ReportTask> report_tasks { get; set; }
    }
    
    public class Department
    {
        public int id { get; set; }
        public string name { get; set; }
    }
    
    public class Result
    {
        public List<List> list { get; set; }
        public List<Department> departments { get; set; }
    }
    
    public class RootObject
    {
        public bool status { get; set; }
        public string message { get; set; }
        public int code { get; set; }
        public Result result { get; set; }
    }

    Wednesday, January 29, 2020 5:57 AM
  • User753101303 posted

    Seems you are looking for https://benjii.me/2018/01/expression-projection-magic-entity-framework-core/

    There is no need to loop. You can "map" incoming data to the class/properties you need to load. 

    Wednesday, January 29, 2020 9:16 AM