How to check if a message is a valid json message?

Does the simple json have a method that tests if the string is a valid json message?

    private bool IsValidJson(string jsonString)
    {
        try
        {
            JsonUtility.FromJsonOverwrite(jsonString, new object());
            return true;
        }
        catch (System.Exception)
        {
            return false;
        }
    }
3 Likes

What validity means? An invalid JSON may mean several things:

  1. Invalid syntax, so it can’t be parsed,
  2. Invalid structure, so it parses wrongly or incompletely,
  3. Missing parts or specification, so it parses correctly, but is understood wrongly or incompletely.

To solve (1) go with the previous post.
To solve (2) you need to do a sanity check of your own, and assert or mandate certain parts.
To solve (3) you need to build a proper layout schematics, or use serialization with fully-fledged objects.

2 Likes