-2

What is the appropriate signature for a method that is returning a json object in a console app?

I can return a list of employees with a method doing the following:

public List<Employee> GetListOfEmployees();

What should the signature of my method be if I wand the same list to be returned as JSON?

Yandroide
  • 91
  • 1
  • 4
  • 13
  • Thank you @David. That's all I needed to know. Now people, if that helps to downgrade my question, please go ahead, but know that there are people out there like myself who need this kind of help. Cheers! – Yandroide Jan 23 '19 at 15:40

1 Answers1

3

JSON isn't a class in C#. It's a standard format for data serialization. You'd either return an object to be serialized by consuming code:

public List<Employee> GetListOfEmployees()
{
    // return a List<Employee>
}

Or return a string representing the serialized object:

public string GetListOfEmployees()
{
    // serialize a List<Employee> to a string and return the string
}

As for how to serialize the object, there are a variety of ways to do that. You could even return a string literal that you manually wrote which represents the object, it makes no difference to the consuming code as long as it's valid JSON.

David
  • 208,112
  • 36
  • 198
  • 279
  • Which of the two signatures is the best practice? – Géry Ogam Jul 29 '19 at 16:47
  • @Maggyero: There isn't a universal best practice, it's entirely based on what you need your methods to return and where the serialization should take place. The methods in this answer include no such context. – David Jul 29 '19 at 16:48
  • Let's say that you have a simple application called JSON Diff with a single `compare` method that takes two JSON input documents and returns a JSON output document listing the differences. It is used like this: `app = JSONDiff(); output_doc = app.compare(input_doc_1, input_doc_2);` Should the parameter types and return value type of the `compare` method be serialized strings (either character strings or encoded byte strings) or deserialized objects? – Géry Ogam Jul 30 '19 at 06:17