0

I Have an object

public class GeneralResponseClass
{
    public int ErrorCode { set; get; }
    public string Date { set; get; }
    public String ErrorMessage { set; get; }

    public List<dynamic> Data = new List<dynamic>();
    public bool Success { set; get; }
    public GeneralResponseClass()
    {
        Date = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
    }
}

in my API Function i want to return the object

[HttpGet]
public GeneralResponseClass Get()
    {
        GeneralResponseClass generalResponseClass = new GeneralResponseClass();

        generalResponseClass.ErrorCode = 0;
        generalResponseClass.ErrorMessage = "";


        generalResponseClass.Success = false;



        generalResponseClass.Data.Add(new
        {
            Name = "User 1",
            Email = "[email protected]"
        });

        generalResponseClass.Data.Add(new
        {
            Name = "User 2",
            Email = "[email protected]"
        });

        return generalResponseClass;
    }

in the response i get don't get the List

 {
   errorCode: 0,
date: "06/01/2020 16:32:12",
errorMessage: "",
success: false
}

Why The List Data dont return?

3
  • In .Net Core it is Possible. Commented Jan 6, 2020 at 14:46
  • Anonymous types are just syntactical sugar. When compiled, a class is generated for it but your application has no scope of this type other than at compile time. Its the same as if you were to use List<object>. The JSON serialiser doesn't have any type information to reflect thus nothing returns. Commented Jan 6, 2020 at 14:46
  • 1
    Please post your API serializer settings if you have defined any. My guess is, you defined it as a field and may be serializer settings are preventing to deserialize it. Try making it a property instead of Field. Commented Jan 6, 2020 at 14:52

1 Answer 1

2

You cannot return any collection with anonymous object. You can use ExpandoObject which is simillar to anonymous. You can also create a custom class for your type of object since they have the same properties in your case (at least in the template).

You can check for more on ExpandoObject here: What are the true benefits of ExpandoObject?

Sign up to request clarification or add additional context in comments.

6 Comments

IMHO, I don't think its issue with dynamic objects. Because in our API, there are dynamic objects returned without any issue.
I meant anonymous, my bad
Agree, dynamic is bad but you did not answer the OP's question on why unable to deserialize. you showed alternative instead.
"How to return a dynamic object list from web api in c#" I guess that's OP's question
That's fine as long as you have helped OP.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.