EN VI

How can i create and convert json a class with less property in c#?

2024-03-13 15:30:05
How can i create and convert json a class with less property in c#?

We are developing a c# api project. We want to serialize a class with 3 properties but this class has 10 properties inside it. How can i create and convert json this class with 3 properties ? I want to generate a json string with this 3 property.

public class SampleClass
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
public string Prop4 { get; set; }
public string Prop5 { get; set; }
public string Prop6 { get; set; }
public string Prop7 { get; set; }
public string Prop8 { get; set; }
public string Prop9 { get; set; }
public string Prop10 { get; set; }
}

var myObj = new MyClass
    {
        Prop1 = "Value 1",
        Prop2 = "Value 2",
        Prop3 = "Value 3"
    };

Solution:

You could use JsonIgnoreAttribute:

public class SampleClass
{
    public string Prop1 { get; set; }

    public string Prop2 { get; set; }

    public string Prop3 { get; set; }

    [JsonIgnore]
    public string Prop4 { get; set; }

    [JsonIgnore]
    public string Prop5 { get; set; }

    [JsonIgnore]
    public string Prop6 { get; set; }

    [JsonIgnore]
    public string Prop7 { get; set; }

    [JsonIgnore]
    public string Prop8 { get; set; }

    [JsonIgnore]
    public string Prop9 { get; set; }

    [JsonIgnore]
    public string Prop10 { get; set; }
}

Reference: How to ignore properties with System.Text.Json

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login