Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to make JsonConvert.DeserializeObject<T>() return null when json format mismatching? #2225

Closed
SolarianZ opened this issue Nov 27, 2019 · 3 comments

Comments

@SolarianZ
Copy link

How to make JsonConvert.DeserializeObject() return null when json format mismatching?

@bartelink
Copy link

define 'mismatching' with an example ? In general, malformed json (or json not passing validation constraints) triggers exceptions for this library. You can trap those, but that's a questionable thing to do.

@SolarianZ
Copy link
Author

For example:

ConditionSetting settingObj = new ConditionSetting();
string settingJson = JsonConvert.SerializeObject(settingObj);
// trying to parse a 'ObjectLayout' object from a 'ConditionSetting' json.
// here i expect to got a null return value or an exception, 
// but infact i got a non-null 'ObjectLayout' object
ObjectLayout layoutObj = JsonConvert.DeserializeObject<ObjectLayout>(settingJson);
print(layoutObj == null); // console print False

Class definitions:

// ObjectLayout.cs
[System.Serializable]
public class ObjectLayout
{
    public bool IsSettled;
    public string Name;
    public Position Position;
    public Rotation Rotation;
}

// ConditionSetting.cs
[System.Serializable]
public class ConditionSetting
{
    public string PlanName;
    public Env Env;
    public Target Target;
    public Tank Tank;
    public int TankCount;
    public Shell Shell;
    public Fuze Fuze;
}
/////////////////////////////////////////////////////////////////////////////////

@JamesNK
Copy link
Owner

JamesNK commented Nov 28, 2019

If JSON values are required then you can put the [Required] attribute on them.

@JamesNK JamesNK closed this as completed Nov 28, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants