Skip to content

Commit 88b5938

Browse files
committed
InnerContentConnector - adds TryParse for the JToken conversion
If a value is detected as JSON, but isn't actually valid JSON, e.g. a string such as "[hello world]", then the `JToken.Parse` will throw an exception. This patch introduces a `TryParse` style method to indicate whether the JToken conversion was successful.
1 parent 16cd10d commit 88b5938

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

src/Umbraco.Deploy.Contrib.Connectors/ValueConnectors/InnerContentConnector.cs

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,8 @@ public string GetValue(Property property, ICollection<ArtifactDependency> depend
100100

101101
// test if the value is a json object (thus could be a nested complex editor)
102102
// if that's the case we'll need to add it as a json object instead of string to avoid it being escaped
103-
var jtokenValue = parsedValue != null && parsedValue.ToString().DetectIsJson() ? JToken.Parse(parsedValue.ToString()) : null;
104-
if (jtokenValue != null)
103+
JToken jtokenValue;
104+
if (TryParseJToken(parsedValue, out jtokenValue))
105105
{
106106
parsedValue = jtokenValue;
107107
}
@@ -199,8 +199,8 @@ public void SetValue(IContentBase content, string alias, string value)
199199
{
200200
// test if the value is a json object (thus could be a nested complex editor)
201201
// if that's the case we'll need to add it as a json object instead of string to avoid it being escaped
202-
var jtokenValue = convertedValue.ToString().DetectIsJson() ? JToken.Parse(convertedValue.ToString()) : null;
203-
if (jtokenValue != null)
202+
JToken jtokenValue;
203+
if (TryParseJToken(convertedValue, out jtokenValue))
204204
{
205205
innerContentItem.PropertyValues[key] = jtokenValue;
206206
}
@@ -222,6 +222,26 @@ public void SetValue(IContentBase content, string alias, string value)
222222
content.SetValue(alias, value);
223223
}
224224

225+
private static bool TryParseJToken(object value, out JToken json)
226+
{
227+
json = default(JToken);
228+
229+
if (value == null)
230+
return false;
231+
232+
var s = value.ToString();
233+
if (string.IsNullOrWhiteSpace(s) || s.DetectIsJson() == false)
234+
return false;
235+
236+
try
237+
{
238+
json = JToken.Parse(s);
239+
}
240+
catch { }
241+
242+
return json != null;
243+
}
244+
225245
/// <summary>
226246
/// The typed value stored for Inner Content
227247
/// </summary>

0 commit comments

Comments
 (0)