0

I have a C# class with a public method as below. I want to serialize this class in JSON using Newtownsoft. The problem is Json serialization only serialize public properties and fields. How would I get method serialized ?

     public class Employee
        {
            public void ExecuteSomeOperation()
            {
                //code...
            }
        }
Renan Araújo
  • 3,533
  • 11
  • 39
  • 49
Pinal Dave
  • 533
  • 4
  • 14
  • 27

3 Answers3

7

You cannot serialize a C# method to a JSON object representation.

Tomáš Hübelbauer
  • 9,179
  • 14
  • 63
  • 125
1

What would you expect to be serialized? 'code' is not normally serialized. However, probably you mean to serialize the 'output' of the function. This will probably contain of properties or variables, so create properties or variables and set them from this method; than the properties/variables will be serialized as such.

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
  • 1
    well.. if the code is nice enough to allow decompiling, see this discussion... http://stackoverflow.com/questions/2693881/c-sharp-can-i-use-reflection-to-inspect-the-code-in-a-method and then when you have extracted the decompiled code, add that to the json data... – Henrik Nov 19 '15 at 12:07
0

This is a binary serialization. You can't use json as you've already said yourself.

I am sure that you will adapt the next code sample for your case:

Serialize sample

Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();

Console.WriteLine("Writing Employee Information");
bformatter.Serialize(stream, mp);
stream.Close();

Deserialize sample

//Open the file written above and read values from it.
stream = File.Open("EmployeeInfo.osl", FileMode.Open);
bformatter = new BinaryFormatter();

Console.WriteLine("Reading Employee Information");
mp = (Employee)bformatter.Deserialize(stream);
stream.Close();
yurart
  • 593
  • 1
  • 6
  • 23
  • OP states they want to serialize to JSON, which is textual, not binary serialization, thus unable to represent executable code. – Tomáš Hübelbauer Nov 19 '15 at 11:57
  • I don't think he has a lack of understanding about serialization. So we have only one thing left - guess what he asks about :) – yurart Nov 19 '15 at 12:00