I am using Visual Studio 2022 with .Net 4.8. So I was not able to use System.Text.Json (Element does not exist) as above explained. I am aware of externally linking this library from NuGet, but as I am a great fan of the NewtonSoft.Json solution, I will use this here in my fully functional example.
Example:
My example wants to make a printable version of my special Jira issue (atlassian issue tracker). I also make use of the JsonSerializer. Because the object is not "flat" and has loops inside, and also has some irrelevant but disturbingly high amount of data inside of a property ("Jira"), I wanted two things to achieve here:
- Printable Version of my object without having to access each property
- Excluding one complex property from getting serialized to Json
- Using flat structure and avoid circular references
So my method has a different signature with two arguments, and I am using the slightly different method JsonConvert. Here I can serialize my object easily, I can put a formatting - here to indented - (for printing out), and I can exclude loops and the "mother" object (in this case Jira). To make this excluding of the property 'Jira' working I use the 'IgnorePropertiesResolver : DefaultContractResolver' from this [solution][1]:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using Atlassian.Jira;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace JIRA_SDK
{
internal class Program
{
static void Main(string[] args)
{
Task1();
Console.ReadKey();
}
private async static void Task1()
{
var jira = Jira.CreateRestClient("URL", "user", "passw");
// use LINQ syntax to retrieve issues
var issues = from i in jira.Issues.Queryable
where i.Assignee == "user"
orderby i.Created
select i;
foreach (var issue in issues)
{
System.Console.WriteLine(JsonConvert.SerializeObject(issue, Formatting.Indented,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new IgnorePropertiesResolver(new[] { "Jira" })
}));
}*/
Console.ReadKey();
}
}
//short helper class to ignore some properties from serialization
public class IgnorePropertiesResolver : DefaultContractResolver
{
private readonly HashSet<string> _ignoreProps;
public IgnorePropertiesResolver(IEnumerable<string> propNamesToIgnore)
{
this._ignoreProps = new HashSet<string>(propNamesToIgnore);
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (this._ignoreProps.Contains(property.PropertyName))
{
property.ShouldSerialize = _ => false;
}
return property;
}
}
}```
[1]: https://stackoverflow.com/questions/63299905/custom-json-contract-resolver-to-ignore-all-properties-without-a-custom-annotation#answer-63305934