1

I have an object class that has the following variables:

class empleado
{
    public string nombre = "Nicolas";
    public string apellido = "Flores";
    public int edad= 22;
}

And I can generate a Json with this line of code:

string jsonResult = JsonConvert.SerializeObject(empleado);

But to the json that generates I would like to add other data apart from the object, how could I do it?

3
  • You don't want to add new properties to your empleado class, do you? Commented Nov 12, 2019 at 2:04
  • Use properties or addorn those fields with JsonPropoerty attribute Commented Nov 12, 2019 at 2:05
  • @Yeheshuah Yes, I don't want to add more properties because I want to show list of employee objects and then add some attributes or messages to that JSON Commented Nov 12, 2019 at 2:10

4 Answers 4

4

As another approach, you can keep a separate model like this. So you can assign your empleado object and other properties you want to it and then convert it to a Json object.

class MyJsonObjectModel
{
    public string otherProperty1 = "My string 1";
    public string otherProperty2 = "My string 2";
    public int otherProperty3 = "1";

    public empleado empleadoModel;
}

string jsonResult = JsonConvert.SerializeObject(MyJsonObjectModel);
Sign up to request clarification or add additional context in comments.

1 Comment

BTW. This uses Json.NET, but for the record, as of .NET Core 3.0 System.Text.Json.JsonSerializer does not serialise fields (as opposed to properties)
2

You cam use a anonymous type.

var o = new {
 P1 = "X",
 P2 = 2,
 empleado.nombre,
 empleado.apellido,
 empleado.edad
};

string jsonResult = JsonConvert.SerializeObject (o);

or

var o = new {
P1 = "X",
P2 = 2,
Emp = empleado
};

string jsonResult = JsonConvert.SerializeObject (o);

1 Comment

BTW. This uses Json.NET, but for the record, as of .NET Core 3.0 System.Text.Json.JsonSerializer does not serialise fields (as opposed to properties)
1

The two methods I prefer are:

1) Create a new class in the same file as your serialization (or wherever you want but I like to keep custom items like that in the same file as the requesting code unless it's reusable) that has all the fields from empleado and add whatever other fields to it you need. For example:

class customempleado
{
    public string nombre = "Nicolas";
    public string apellido = "Flores";
    public int edad= 22;
    public string moredata1 = "More data 1";
    public string moredata2 = "More data 2";
}

2) Serialize a anonymous object and add the class and new data to it. For example:

string jsonResult = JsonConvert.SerializeObject ( new { nombre = "Nicolas", apellido = "Flores", edad = 22, moredata1 = "More data", moredata2 = moredata2 });

Comments

1

Here's one way of performing all CRUD type operations on a de-serialized JSON object:

public static void ManipulateJsonObject()
{

    string json =
    @"{
        ""empleado"": {
            ""nombre"": ""My nombre"",
            ""apellido"": ""My apellido"",
            ""edad"": 1
        }
    }";

    JObject baseJObject = JObject.Parse(json);


    System.Diagnostics.Trace.WriteLine("JObject before modifications, just after parse:");
    System.Diagnostics.Trace.WriteLine(baseJObject.ToString());

    // Get node with name 'empleado'
    JObject empleadoNode = (JObject)baseJObject["empleado"];

    // Create new property 'afterNombre'
    empleadoNode.Property("nombre").AddAfterSelf(new JProperty("afterNombre", "new nombre value"));

    System.Diagnostics.Trace.WriteLine("Observe newly added property 'afterNobre':");
    System.Diagnostics.Trace.WriteLine(baseJObject.ToString());

    // Read value of new property 'afterNombre'
    string empleadoValue = (string) empleadoNode["afterNombre"];

    // Throws exception if value was not set
    if(string.IsNullOrWhiteSpace(empleadoValue))
        throw new Exception("Adding or Reading new property failed");

    // Update value of existing property 'edad'
    empleadoNode["edad"] = 3;

    System.Diagnostics.Trace.WriteLine("Observe newly property 'edad' has been updated:");
    System.Diagnostics.Trace.WriteLine(baseJObject.ToString());

    // Delete newly added property 'afterNombre'
    empleadoNode.Property("afterNombre").Remove();

    System.Diagnostics.Trace.WriteLine("Observe property 'afterNobre' has been deleted:");
    System.Diagnostics.Trace.WriteLine(baseJObject.ToString());
    // Output final object

    System.Diagnostics.Trace.WriteLine("Final state of JObject:");
    System.Diagnostics.Trace.WriteLine(baseJObject.ToString());
}

See visual studio Output window for inspection result after each manipulation.

Comments

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.