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

Fixed issue https://github.com/JamesNK/Newtonsoft.Json/issues/2924 #2925

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions Src/Newtonsoft.Json.Tests/JsonConvertTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,18 @@ public void PopulateObjectWithNoContent()
JsonConvert.PopulateObject(json, o);
}, "No JSON content found. Path '', line 0, position 0.");
}

[Test]
public void PopulateObjectInvalidJson()
{
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
string json = "{\"test\":1}gg";

PopulateTestObject o = new PopulateTestObject();
JsonConvert.PopulateObject(json, o);
}, "Invalid JSON string. Path '', line 1, position 10.");
}

[Test]
public void NoConstructorName() {
Expand Down
18 changes: 17 additions & 1 deletion Src/Newtonsoft.Json/JsonConvert.cs
Original file line number Diff line number Diff line change
Expand Up @@ -857,10 +857,26 @@ public static void PopulateObject(string value, object target)
public static void PopulateObject(string value, object target, JsonSerializerSettings? settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);

using (JsonReader jsonReader = new JsonTextReader(new StringReader(value)))
{
jsonSerializer.Populate(jsonReader, target);

// check if value is a valid JSON string
try
{
if (!string.IsNullOrEmpty(value) && value.StartsWith("{"))
{
var jObject = JObject.Parse(value);
} else if (!string.IsNullOrEmpty(value) && value.StartsWith("["))
{
var jArray = JArray.Parse(value);
}
}
catch (Exception)
{
throw JsonSerializationException.Create(jsonReader, "Invalid JSON string.");
}

if (settings != null && settings.CheckAdditionalContent)
{
Expand Down