1

因此,我一直在使用最新的 Web API 程序集开发 WCF Web 服务,并且我喜欢 JsonValue 对象。

我想要做的是接受绑定到 JsonValue 对象的 JSON,然后将该 JsonValue 对象转换为等效的 XML 表示形式,该表示形式可以传递到存储过程中进行处理。这消除了创建对象以将 JsonValue 绑定到的需要,这使事情保持流畅。

然后我希望能够以 XML 格式从数据库中选择数据,然后将其转换为 JsonValue 以返回给客户端。

我已经能够通过这种扩展方法将 JsonValue 转换为 XML 的字符串表示形式:

// Convert JsonValue to XML string
public static string ToXmlString(this JsonValue instance) {
    using (var ms = new MemoryStream()) {
        using (var xdw = XmlDictionaryWriter.CreateTextWriter(ms)) {
            instance.Save(xdw);
            xdw.Flush();
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }
}

有一个更好的方法吗?这种方法很好,但我只是想知道。

我还能够使用 Json.NET 库将 XML 字符串值转换回 JsonValue 以将 XML 字符串转换为 JSON 字符串,然后将字符串加载到 JsonValue 对象中,如下所示:

// Return JSON representation of XML
return JsonValue.Parse(JsonConvert.SerializeXNode(xmlElement, Formatting.None, true));

这种方法很好,但我不想依赖 Json.NET 库,因为我仅将它包含在这个方法中。有没有办法在不使用 Json.NET 库的情况下做到这一点?

提前感谢您的帮助!

丹尼尔

4

2 回答 2

1

您的转换代码很好。要将 XML 转换回 JsonValue,您可以使用JsonValueExtensionsWeb API 中的类:

// Convert JsonValue to XML string
public static string ToXmlString(this JsonValue instance) {
    using (var ms = new MemoryStream()) {
        using (var xdw = XmlDictionaryWriter.CreateTextWriter(ms)) {
            instance.Save(xdw);
            xdw.Flush();
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }
}

// Convert XML string to JsonValue
public static JsonValue FromXmlString(this string jsonAsXml) {
    using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonAsXml))) {
        using (var xdr = XmlDictionaryReader.CreateTextReader(ms, XmlDictionaryReaderQuotas.Max))) {
            return JsonValueExtensions.Load(xdr);
        }
    }
}
于 2011-11-03T18:23:27.413 回答
0

这对你不起作用吗?

XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
于 2011-11-03T13:55:12.063 回答