How to JsonConvert.SerializeObject after object cast? [duplicate] - c#

This question already has answers here:
How to exclude property from Json Serialization
(9 answers)
Closed 5 years ago.
How to JsonConvert.SerializeObject after object cast?
I have two classes like this example, and I want my serialized json to not include the "Id" field.
public class Person : Description
{
public int Id { get; set; }
}
public class Description
{
public string Name { get; set; }
}
Person person = new Person() { Id = 1, Name = "Bill" };
Description description = person;
string jsonDescription = JsonConvert.SerializeObject(description);
Console.WriteLine(jsonDescription);
// {"Id":1,"Name":"Bill"}
I've tried several things like casting with "as" or casting with .Cast() but no luck yet.
Thank you for your suggestions.

Just use the JsonIgnore attribute.
public class Person : Description
{
[JsonIgnore]
public int Id { get; set; }
}

Related

Dynamically ignore property on sealed class when serializing JSON with System.Text.Json [duplicate]

This question already has answers here:
How to exclude a property from being serialized in System.Text.Json.JsonSerializer.Serialize() using a JsonConverter
(5 answers)
System.Text.Json API is there something like IContractResolver
(2 answers)
Closed 2 years ago.
Question
Can I dynamically ignore a property from a sealed class using System.Text.Json.JsonSerializer?
Example Code
Example class from another library:
public sealed class FrozenClass
{
// [JsonIgnore] <- cannot apply because I don't own this class
public int InternalId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Default Serialization:
var person = new FrozenClass() { InternalId = 3, FirstName = "Dorothy", LastName = "Vaughan" };
var jsonString = System.Text.Json.JsonSerializer.Serialize(person);
Actual Outcome:
{ "InternalId": 3, "FirstName": "Dorothy", "LastName": "Vaughan" }
Expected Outcome:
{ "FirstName": "Dorothy", "LastName": "Vaughan" }
Alternatives that don't work
There are two other questions on how to add JsonIgnore at RunTime & add dynamic property name for serialization, but both are targeted at Newtonsoft's Json.NET - and often reference this extension method
There are several ways to modify the way a class is serialized with the native JsonSerializer, but all seem to rely on modifying the underlying class:
You can exclude properties from serialization by adding the [JsonIgnore] attribute to the original class
You can register a JsonConverter on a property by adding the [JsonConverter] attribute to the original class
However, in my case, the class is from another library and cannot be extended
Workarounds
A possible workaround is to create another exportable class and setup a mapper between them
public class MyFrozenClass
{
public MyFrozenClass(FrozenClass frozen)
{
this.FirstName = frozen.FirstName;
this.LastName = frozen.LastName;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
var jsonString = System.Text.Json.JsonSerializer.Serialize(new MyFrozenClass(person));

Trying serialize to json only the base class [duplicate]

This question already has an answer here:
How to exclude properties from JsonConvert.PopulateObject that don't exist in some base type or interface?
(1 answer)
Closed 3 years ago.
I am trying to save the following data in the Json form. I am using the Newtonsoft.Json library for that. Sometimes I need to serialize only the RecipeShort properties of the Recipe object.
[JsonObject(MemberSerialization.OptIn)]
public class RecipeShort
{
[JsonProperty]
public string Id { get; set; }
[JsonProperty]
public string Title { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class Recipe : RecipeShort
{
[JsonProperty]
private List<Ingredient> ingredients;
[JsonProperty]
public string Method { get; set; }
}
Recipe res = new Recipe
{
Id = "123",
Title = "Text",
Method ="Text",
Ingredients = ingredients
};
I've tried several ways but it did not work.
One way:
string str1 = Newtonsoft.Json.JsonConvert.SerializeObject(res, typeof(RecipeShort),null);
Other way:
RecipeShort temp = (RecipeShort) res;
string str1 = Newtonsoft.Json.JsonConvert.SerializeObject((RecipeShort)temp, typeof(RecipeShort),null);
The third way:
string str = Newtonsoft.Json.JsonConvert.SerializeObject(res);
RecipeShort temp1 = Newtonsoft.Json.JsonConvert.DeserializeObject<RecipeShort>(str);
string str1 = Newtonsoft.Json.JsonConvert.SerializeObject(temp1, typeof(RecipeShort),null);
First two ways are fully serialize the object. The third fails on attempt to deserialize with NullPointerExeption.
Is there any elegant way to serialize only the base class without doing it manually?
You can probably use IContractResolver, see https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm.

C# dynamically set property When Property is a class? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
Hi i have a Number of Properties and My properties like
public XYZ()
{
xyz = new xyz1();
xyz2 = new xyz2();
}
public xyz1 xyz1 { get; set; }
public xyz2 xyz2 { get; set; }
}
public class xyz1
{
public string fName { get; set; }
public string lnameget; set;}
}
public class xyz2
{
public string city { get; set; }
public string state
}
While i am setting my property on runtime i am getting exception object reference set to null.
XYZ model = new XYZ();
PropertyInfo propertyInfo = model.GetType().GetProperty("fName");
propertyInfo.SetValue(model, Convert.ChangeType(item.InnerText, propertyInfo.PropertyType), null);
Please help me
model has no fName property, but model.xyz1 does.

JsonConvert.DeserializeObject not working on 1 specific object ("$id") returns null is empty [duplicate]

This question already has answers here:
JsonConvert.DeserializeObject<> (string) returns null value for $id property
(3 answers)
Closed 7 years ago.
This are my models:
public class Object
{
[JsonProperty(PropertyName = "test1")]
public string Test1 { get; set; }
[JsonProperty(PropertyName = "test2")]
public string Test2 { get; set; }
[JsonProperty(PropertyName = "_id")]
public ID Id { get; set; }
}
public class ID
{
[JsonProperty(PropertyName = "$id")]
public string Id { get; set; }
}
When I debug it show every value correctly, but after the JsonConvert. Id is empty. What am I doing wrong here?
Json body:
"test1: "sometext",
"test2": "sometext",
"_id": {
"$id": "thisisanidstring"
}
This question is already there Have a look.
Json.NET uses $id as a reserved word to help it deal with object references.

Json.net How do I serialize or deserialize all property , even include non [DataMember]? [duplicate]

This question already has answers here:
Configure JSON.NET to ignore DataContract/DataMember attributes
(6 answers)
Closed 7 years ago.
I'm using Json.net(Newtonsoft.Json) to serialize or deserialize some class.
There is my class
[DataContract]
Public class Person
{
[DataMember]
public string ID { get; set; }
}
public class Student : Person
{
public string StudentName { get; set;}
}
Now I want to serialize student, But Looks like Json.net only serialize or deserialize DataContract class and DataMember property. It always ignore my StudentName property, But I need it include in.
Is there any way to fixed this? thank you.
According to official site you just have to add [DataMember] attribute to StudentName to have this property in the json string.
If you need to include the StudentName property just add [DataMember] attribute to this property.
However, another easier way can be to completely remove [DataContract] and [DataMember] as Newtonsfot.Json doesn't really need them to determine which properties to include.
public class Person
{
public string ID { get; set; }
}
public class Student : Person
{
public string StudentName { get; set;}
}
// ...
Student student = new Student() { ID = "1", StudentName = "John" };
string resultJson = Newtonsoft.Json.JsonConvert.SerializeObject(student);

Categories

Resources