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

Created on 27 Nov 2019  路  3Comments  路  Source: JamesNK/Newtonsoft.Json

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

Most helpful comment

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

All 3 comments

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.

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;
}
/////////////////////////////////////////////////////////////////////////////////

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

Was this page helpful?
0 / 5 - 0 ratings