-Fixed converting JSON to XML

-Fixed not including line data with many XmlNodeConverter exceptions
This commit is contained in:
James Newton-King
2015-09-30 17:35:53 +13:00
parent c007f066a1
commit eccdf4bf95
2 changed files with 268 additions and 63 deletions
@@ -427,7 +427,7 @@ namespace Newtonsoft.Json.Tests.Converters
{ {
JsonConvert.DeserializeXmlNode(json); JsonConvert.DeserializeXmlNode(json);
}, },
"JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName."); "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName. Path 'Email', line 3, position 14.");
} }
[Test] [Test]
@@ -944,7 +944,9 @@ namespace Newtonsoft.Json.Tests.Converters
[Test] [Test]
public void RootObjectMultipleProperties() public void RootObjectMultipleProperties()
{ {
ExceptionAssert.Throws<JsonSerializationException>(() => { XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"{Prop1:1,Prop2:2}"); }, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName."); ExceptionAssert.Throws<JsonSerializationException>(
() => { XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"{Prop1:1,Prop2:2}"); },
"JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName. Path 'Prop2', line 1, position 15.");
} }
[Test] [Test]
@@ -1060,7 +1062,9 @@ namespace Newtonsoft.Json.Tests.Converters
{ {
string json = @"{""count"": 773840,""photos"": null}"; string json = @"{""count"": 773840,""photos"": null}";
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeXmlNode(json); }, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName."); ExceptionAssert.Throws<JsonSerializationException>(
() => { JsonConvert.DeserializeXmlNode(json); },
"JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName. Path 'photos', line 1, position 26.");
} }
#if !NET20 #if !NET20
@@ -1069,7 +1073,9 @@ namespace Newtonsoft.Json.Tests.Converters
{ {
string json = @"{""count"": 773840,""photos"": null}"; string json = @"{""count"": 773840,""photos"": null}";
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeXNode(json); }, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName."); ExceptionAssert.Throws<JsonSerializationException>(
() => { JsonConvert.DeserializeXNode(json); },
"JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName. Path 'photos', line 1, position 26.");
} }
#endif #endif
@@ -1436,6 +1442,162 @@ namespace Newtonsoft.Json.Tests.Converters
StringAssert.AreEqual(expectedXmlJson, xmlJson); StringAssert.AreEqual(expectedXmlJson, xmlJson);
} }
[Test]
public void SerializeDeserializeMetadataArray()
{
string json = @"{
""$id"": ""1"",
""$values"": [
""1"",
""2"",
""3"",
""4"",
""5""
]
}";
XmlNode node = JsonConvert.DeserializeXmlNode(json, "root");
string xml = GetIndentedInnerXml(node);
StringAssert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-16""?>
<root xmlns:json=""http://james.newtonking.com/projects/json"" json:id=""1"">
<values xmlns=""http://james.newtonking.com/projects/json"">1</values>
<values xmlns=""http://james.newtonking.com/projects/json"">2</values>
<values xmlns=""http://james.newtonking.com/projects/json"">3</values>
<values xmlns=""http://james.newtonking.com/projects/json"">4</values>
<values xmlns=""http://james.newtonking.com/projects/json"">5</values>
</root>", xml);
string newJson = JsonConvert.SerializeXmlNode(node, Formatting.Indented, true);
StringAssert.AreEqual(json, newJson);
}
[Test]
public void SerializeDeserializeMetadataArrayNoId()
{
string json = @"{
""$values"": [
""1"",
""2"",
""3"",
""4"",
""5""
]
}";
XmlNode node = JsonConvert.DeserializeXmlNode(json, "root");
string xml = GetIndentedInnerXml(node);
StringAssert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-16""?>
<root xmlns:json=""http://james.newtonking.com/projects/json"">
<values xmlns=""http://james.newtonking.com/projects/json"">1</values>
<values xmlns=""http://james.newtonking.com/projects/json"">2</values>
<values xmlns=""http://james.newtonking.com/projects/json"">3</values>
<values xmlns=""http://james.newtonking.com/projects/json"">4</values>
<values xmlns=""http://james.newtonking.com/projects/json"">5</values>
</root>", xml);
string newJson = JsonConvert.SerializeXmlNode(node, Formatting.Indented, true);
Console.WriteLine(newJson);
StringAssert.AreEqual(json, newJson);
}
[Test]
public void SerializeDeserializeMetadataArrayWithIdLast()
{
string json = @"{
""$values"": [
""1"",
""2"",
""3"",
""4"",
""5""
],
""$id"": ""1""
}";
XmlNode node = JsonConvert.DeserializeXmlNode(json, "root");
string xml = GetIndentedInnerXml(node);
StringAssert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-16""?>
<root xmlns:json=""http://james.newtonking.com/projects/json"" json:id=""1"">
<values xmlns=""http://james.newtonking.com/projects/json"">1</values>
<values xmlns=""http://james.newtonking.com/projects/json"">2</values>
<values xmlns=""http://james.newtonking.com/projects/json"">3</values>
<values xmlns=""http://james.newtonking.com/projects/json"">4</values>
<values xmlns=""http://james.newtonking.com/projects/json"">5</values>
</root>", xml);
string newJson = JsonConvert.SerializeXmlNode(node, Formatting.Indented, true);
StringAssert.AreEqual(@"{
""$id"": ""1"",
""$values"": [
""1"",
""2"",
""3"",
""4"",
""5""
]
}", newJson);
}
[Test]
public void SerializeMetadataPropertyWithBadValue()
{
string json = @"{
""$id"": []
}";
ExceptionAssert.Throws<JsonSerializationException>(
() => { JsonConvert.DeserializeXmlNode(json, "root"); },
"Unexpected JsonToken: StartArray. Path '$id', line 2, position 11.");
}
[Test]
public void SerializeDeserializeMetadataWithNullValue()
{
string json = @"{
""$id"": null
}";
XmlNode node = JsonConvert.DeserializeXmlNode(json, "root");
string xml = GetIndentedInnerXml(node);
StringAssert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-16""?>
<root xmlns:json=""http://james.newtonking.com/projects/json"" json:id="""" />", xml);
string newJson = JsonConvert.SerializeXmlNode(node, Formatting.Indented, true);
StringAssert.AreEqual(@"{
""$id"": """"
}", newJson);
}
[Test]
public void SerializeDeserializeMetadataArrayNull()
{
string json = @"{
""$id"": ""1"",
""$values"": null
}";
XmlNode node = JsonConvert.DeserializeXmlNode(json, "root");
string xml = GetIndentedInnerXml(node);
StringAssert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-16""?>
<root xmlns:json=""http://james.newtonking.com/projects/json"" json:id=""1"">
<values xmlns=""http://james.newtonking.com/projects/json"" />
</root>", xml);
string newJson = JsonConvert.SerializeXmlNode(node, Formatting.Indented, true);
StringAssert.AreEqual(json, newJson);
}
[Test] [Test]
public void EmptyPropertyName() public void EmptyPropertyName()
{ {
@@ -1518,7 +1680,9 @@ namespace Newtonsoft.Json.Tests.Converters
} }
}"; }";
ExceptionAssert.Throws<JsonSerializationException>(() => { DeserializeXmlNode(json); }, "XmlNodeConverter cannot convert JSON with an empty property name to XML."); ExceptionAssert.Throws<JsonSerializationException>(
() => { DeserializeXmlNode(json); },
"XmlNodeConverter cannot convert JSON with an empty property name to XML. Path '8452309520V2.', line 3, position 10.");
} }
[Test] [Test]
@@ -32,6 +32,7 @@ using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Xml; using System.Xml;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json.Serialization;
#if !(NET20 || PORTABLE40) #if !(NET20 || PORTABLE40)
using System.Xml.Linq; using System.Xml.Linq;
#endif #endif
@@ -995,7 +996,10 @@ namespace Newtonsoft.Json.Converters
case XmlNodeType.Comment: case XmlNodeType.Comment:
return CommentName; return CommentName;
case XmlNodeType.Element: case XmlNodeType.Element:
return ResolveFullName(node, manager); if (node.NamespaceUri == JsonNamespaceUri)
return "$" + node.LocalName;
else
return ResolveFullName(node, manager);
case XmlNodeType.ProcessingInstruction: case XmlNodeType.ProcessingInstruction:
return "?" + ResolveFullName(node, manager); return "?" + ResolveFullName(node, manager);
case XmlNodeType.DocumentType: case XmlNodeType.DocumentType:
@@ -1349,7 +1353,7 @@ namespace Newtonsoft.Json.Converters
private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager)
{ {
if (string.IsNullOrEmpty(propertyName)) if (string.IsNullOrEmpty(propertyName))
throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML."); throw JsonSerializationException.Create(reader, "XmlNodeConverter cannot convert JSON with an empty property name to XML.");
Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager); Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager);
@@ -1358,59 +1362,84 @@ namespace Newtonsoft.Json.Converters
if (propertyName.StartsWith('@')) if (propertyName.StartsWith('@'))
{ {
string attributeName = propertyName.Substring(1); string attributeName = propertyName.Substring(1);
string attributeValue = reader.Value.ToString();
string attributePrefix = MiscellaneousUtils.GetPrefix(attributeName); string attributePrefix = MiscellaneousUtils.GetPrefix(attributeName);
IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) AddAttribute(reader, document, currentNode, attributeName, manager, attributePrefix);
? document.CreateAttribute(attributeName, manager.LookupNamespace(attributePrefix), attributeValue)
: document.CreateAttribute(attributeName, attributeValue);
((IXmlElement)currentNode).SetAttributeNode(attribute);
} }
else else if (propertyName.StartsWith('$'))
{ {
IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager); if (propertyName == JsonTypeReflector.ArrayValuesPropertyName)
currentNode.AppendChild(element);
// add attributes to newly created element
foreach (KeyValuePair<string, string> nameValue in attributeNameValues)
{ {
string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); propertyName = propertyName.Substring(1);
elementPrefix = manager.LookupPrefix(JsonNamespaceUri);
IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) CreateElement(reader, document, currentNode, propertyName, manager, elementPrefix, attributeNameValues);
? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value)
: document.CreateAttribute(nameValue.Key, nameValue.Value);
element.SetAttributeNode(attribute);
}
if (reader.TokenType == JsonToken.String
|| reader.TokenType == JsonToken.Integer
|| reader.TokenType == JsonToken.Float
|| reader.TokenType == JsonToken.Boolean
|| reader.TokenType == JsonToken.Date)
{
element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader)));
}
else if (reader.TokenType == JsonToken.Null)
{
// empty element. do nothing
} }
else else
{ {
// finished element will have no children to deserialize string attributeName = propertyName.Substring(1);
if (reader.TokenType != JsonToken.EndObject) string attributePrefix = manager.LookupPrefix(JsonNamespaceUri);
{ AddAttribute(reader, document, currentNode, attributeName, manager, attributePrefix);
manager.PushScope();
DeserializeNode(reader, document, manager, element);
manager.PopScope();
}
manager.RemoveNamespace(string.Empty, manager.DefaultNamespace);
} }
} }
else
{
CreateElement(reader, document, currentNode, propertyName, manager, elementPrefix, attributeNameValues);
}
}
private void CreateElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string elementName, XmlNamespaceManager manager, string elementPrefix, Dictionary<string, string> attributeNameValues)
{
IXmlElement element = CreateElement(elementName, document, elementPrefix, manager);
currentNode.AppendChild(element);
// add attributes to newly created element
foreach (KeyValuePair<string, string> nameValue in attributeNameValues)
{
string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key);
IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix))
? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value)
: document.CreateAttribute(nameValue.Key, nameValue.Value);
element.SetAttributeNode(attribute);
}
if (reader.TokenType == JsonToken.String
|| reader.TokenType == JsonToken.Integer
|| reader.TokenType == JsonToken.Float
|| reader.TokenType == JsonToken.Boolean
|| reader.TokenType == JsonToken.Date)
{
element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader)));
}
else if (reader.TokenType == JsonToken.Null)
{
// empty element. do nothing
}
else
{
// finished element will have no children to deserialize
if (reader.TokenType != JsonToken.EndObject)
{
manager.PushScope();
DeserializeNode(reader, document, manager, element);
manager.PopScope();
}
manager.RemoveNamespace(string.Empty, manager.DefaultNamespace);
}
}
private static void AddAttribute(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string attributeName, XmlNamespaceManager manager, string attributePrefix)
{
string attributeValue = reader.Value.ToString();
IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix))
? document.CreateAttribute(attributeName, manager.LookupNamespace(attributePrefix), attributeValue)
: document.CreateAttribute(attributeName, attributeValue);
((IXmlElement) currentNode).SetAttributeNode(attribute);
} }
private string ConvertTokenToXmlValue(JsonReader reader) private string ConvertTokenToXmlValue(JsonReader reader)
@@ -1551,10 +1580,6 @@ namespace Newtonsoft.Json.Converters
} }
break; break;
case '$': case '$':
attributeName = attributeName.Substring(1);
reader.Read();
attributeValue = reader.Value.ToString();
// check that JsonNamespaceUri is in scope // check that JsonNamespaceUri is in scope
// if it isn't then add it to document and namespace manager // if it isn't then add it to document and namespace manager
string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri); string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri);
@@ -1572,6 +1597,22 @@ namespace Newtonsoft.Json.Converters
manager.AddNamespace(jsonPrefix, JsonNamespaceUri); manager.AddNamespace(jsonPrefix, JsonNamespaceUri);
} }
// special case $values, it will have a non-primitive value
if (attributeName == JsonTypeReflector.ArrayValuesPropertyName)
{
finishedAttributes = true;
break;
}
attributeName = attributeName.Substring(1);
reader.Read();
if (!JsonTokenUtils.IsPrimitiveToken(reader.TokenType))
{
throw JsonSerializationException.Create(reader, "Unexpected JsonToken: " + reader.TokenType);
}
attributeValue = (reader.Value != null) ? reader.Value.ToString() : null;
attributeNameValues.Add(jsonPrefix + ":" + attributeName, attributeValue); attributeNameValues.Add(jsonPrefix + ":" + attributeName, attributeValue);
break; break;
default: default:
@@ -1581,7 +1622,6 @@ namespace Newtonsoft.Json.Converters
} }
else else
{ {
finishedAttributes = true; finishedAttributes = true;
} }
@@ -1593,7 +1633,7 @@ namespace Newtonsoft.Json.Converters
finishedElement = true; finishedElement = true;
break; break;
default: default:
throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType); throw JsonSerializationException.Create(reader, "Unexpected JsonToken: " + reader.TokenType);
} }
} }
} }
@@ -1625,7 +1665,7 @@ namespace Newtonsoft.Json.Converters
standalone = reader.Value.ToString(); standalone = reader.Value.ToString();
break; break;
default: default:
throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value); throw JsonSerializationException.Create(reader, "Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value);
} }
} }
@@ -1666,7 +1706,7 @@ namespace Newtonsoft.Json.Converters
internalSubset = reader.Value.ToString(); internalSubset = reader.Value.ToString();
break; break;
default: default:
throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value); throw JsonSerializationException.Create(reader, "Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value);
} }
} }
@@ -1691,7 +1731,7 @@ namespace Newtonsoft.Json.Converters
{ {
case JsonToken.PropertyName: case JsonToken.PropertyName:
if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null) if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null)
throw new JsonSerializationException("JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName."); throw JsonSerializationException.Create(reader, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.");
string propertyName = reader.Value.ToString(); string propertyName = reader.Value.ToString();
reader.Read(); reader.Read();
@@ -1725,13 +1765,13 @@ namespace Newtonsoft.Json.Converters
} }
break; break;
case JsonToken.Comment: case JsonToken.Comment:
currentNode.AppendChild(document.CreateComment((string)reader.Value)); currentNode.AppendChild(document.CreateComment((string) reader.Value));
break; break;
case JsonToken.EndObject: case JsonToken.EndObject:
case JsonToken.EndArray: case JsonToken.EndArray:
return; return;
default: default:
throw new JsonSerializationException("Unexpected JsonToken when deserializing node: " + reader.TokenType); throw JsonSerializationException.Create(reader, "Unexpected JsonToken when deserializing node: " + reader.TokenType);
} }
} while (reader.TokenType == JsonToken.PropertyName || reader.Read()); } while (reader.TokenType == JsonToken.PropertyName || reader.Read());
// don't read if current token is a property. token was already read when parsing element attributes // don't read if current token is a property. token was already read when parsing element attributes
@@ -1766,6 +1806,7 @@ namespace Newtonsoft.Json.Converters
{ {
return c.Where(a => a.NamespaceUri != JsonNamespaceUri); return c.Where(a => a.NamespaceUri != JsonNamespaceUri);
} }
#endregion #endregion
/// <summary> /// <summary>
@@ -1778,11 +1819,11 @@ namespace Newtonsoft.Json.Converters
public override bool CanConvert(Type valueType) public override bool CanConvert(Type valueType)
{ {
#if !NET20 #if !NET20
if (typeof(XObject).IsAssignableFrom(valueType)) if (typeof (XObject).IsAssignableFrom(valueType))
return true; return true;
#endif #endif
#if !(DOTNET || PORTABLE) #if !(DOTNET || PORTABLE)
if (typeof(XmlNode).IsAssignableFrom(valueType)) if (typeof (XmlNode).IsAssignableFrom(valueType))
return true; return true;
#endif #endif