I've got a fixedPoint math library objects that have the actual values in a few fields and then like a billion properties that seem to hold converted versions of those values to pass along or something?
I.E.
//important info
public fp x = 0;
public fp y = 0;
//not important info
public fp4 xxxx { get; }
public fp4 xxxy { get; }
public fp4 xxyx { get; }
etc times a billion...
Obviously the only thing I want serialized are the important variables. I spent hours trying to figure out why json was trying to compare variables I didn't make only to find out that it was because of these properties while it was checking for circular references and throwing me tons of errors. And now I'm ripping my hair out over what seems like should be basic functionality XD. Any help would be greatly appreciated. Bonus points if I don't have to edit the library files themselves since that might break if I update from that repo.
To reiterate, I only want to serialize fields. No properties.
Edit: For anyone else having this problem. I couldn't get Newtonsoft to do what I wanted but the regular built-in JsonUtility worked just fine with no extra steps:
JsonUtility.ToJson(data)
I had tried it earlier but had issues, turns out my dumb self had forgotten a [Serializable] tag on one of my structs 😅 Very embarassing.
After that though, I realized that didn't fit some other unrelated needs I had either so I ended up switching to OdinInspectors serializer which ALSO worked fine without any other steps. It even supports serializing System.Object!
Sirenix.Serialization.SerializationUtility.SerializeValue(data, Sirenix.Serialization.DataFormat.JSON);
Clearly what I wanted was basic enough functionality to make the default in other stuff lol.
Thanks to everyone who responded! And for those of you who downvoted, I'm not sure what else you wanted from me ¯\(ツ)/¯
You can use [JsonIgnore]
attribute over unwanted props.
Use this helper https://github.com/jitbit/JsonIgnoreProps. You can specify list of members to ignore.
Use it like
JsonConvert.SerializeObject(
YourObject,
new JsonSerializerSettings() {
ContractResolver = new IgnorePropertiesResolver(new[] { "notImportant1", "notImportant2" })
};
);
NOTE - I didn't test it as have no ability right now, you may need to adjust it
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Reflection;
public class FieldsOnlyContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
// check member types
if (member.MemberType == MemberTypes.Property)
{
property.ShouldSerialize = _ => false; // Ignore all properties
}
return property;
}
}
Then use it like:
var settings = new JsonSerializerSettings
{
ContractResolver = new FieldsOnlyContractResolver()
};
string json = JsonConvert.SerializeObject(yourObj, settings);