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
Array with missing [ is considered a valid JSON #2585
Comments
Not really a bug... There is no json array to be considered. The That JToken.ReadFrom should attempt reading an JSON array when confronted with your "json" string is a misplaced expectation. It reads whatever token (or JSON data type, if you will) it detects, which in this case is just the JSON string If you expect your JSON data to be an array, you can attempt to load it as a JArray by using the JArray.Load method, like: var res = JArray.Load(reader); This will then also throw an exception if no valid JSON array can be obtained from the reader. If all you want is to see whether there is additional text following after the read json value, you could also just call |
If the reason you are using a JsonReader is to configure said JsonReader (and this excluding you from using JToken.Parse) while expecting to read varying input data that is not always an Json array, there is a fourth way of doing this that avoids the explicit call of reader.Read(): using the JsonSerializer. JsonSerializer can actually deserialize into a JToken. The deserializer figures out the concrete JTtoken type (such as JValue, JArray, JObject) by itself: var serializationSettings = new JsonSerializerSettings
{
DateParseHandling = DateParseHandling.None,
CheckAdditionalContent = true // <--- THIS IS VERY IMPORTANT, DO NOT FORGET TO SET THIS
};
var serializer = JsonSerializer.Create(serializationSettings);
var reader = new JsonTextReader(new StringReader(json));
var res = serializer.Deserialize<JToken>(reader); Note that it is required for your use case to set |
Thank you for the explanations @elgonzo . Your last answer is what solved my problem, as I don't know what is the form of the JSON in advance and so I don't know if I am expecting a string, object or an array, etc. |
Source/destination types
Source/destination JSON
Expected behavior
I am expecting an error similar to:
Because according to https://jsonformatter.curiousconcept.com/# it is not a valid JSON:
Actual behavior
No error
Steps to reproduce
The text was updated successfully, but these errors were encountered: