question

Anthony Demanuele avatar image
Anthony Demanuele asked

How to get Json to ignore a property or field?

Both these property/field get serialized. Can I somehow get control on which fields get serialized/ignore?


public float PlayerPoints {get; private set;}


[NonSerialized]
public float PlayerPoints;

Thank you!
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Seth Du avatar image
Seth Du answered

I am not sure of your question, tell us if anything was missed.

If you are trying to ignore property or field when serializing class, setting the NonSerialized attribute is the correct way in Unity. The following is an example:

void Start()  
{ 
	myclass obj = new myclass {num = 123123, a = "test1", b = "test2"};
	string json =
	JsonUtility.ToJson(obj); 
	print(json);  
}

public class myclass  
{
	public int num;
	public string a; 

	[NonSerialized]
	public string b;  
}

The output in the unity client is:

{"num":123123,"a":"test1"}
UnityEngine.MonoBehaviour:print(Object)
test:Start() (at Assets/test.cs:16)

as you can see string b is not serialized due to the [NonSerialized] label.

If it is deserializing JSON string to object and you are looking for a similar way to ignore some properties in the JSON, the answer is NO. JSON is pure data and any other keywords insides should be simple data. If there are specified needs, you can create a designated KVP like “_Serialized”: “(your data here)” or “_NonSerialized”: “(your data here)”. Then create a process to handle their values when receiving this JSON data.

Kindly reminder: this forum is for technical discussions or idea sharing on PlayFab. In terms of Unity or other aspects, you may find more information from official community forum.

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

will-3 avatar image
will-3 answered

Sorry to necro but I'm getting the same problem.

You can't add [NonSerialized] to a property like he showed in the example

 public float PlayerPoints {get; private set;}

Any ideas on how to ignore properties?

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.