问题描述
我正在将xml作为字符串传递
Hi I am passing an xml as string
<AbcDto xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Abc">
<Id>2</Id>
<Description>sample string 4</Description>
<Name>sample string 3</Name>
<PolicyId>c17f5b9f-c9bf-4a3a-b09b-f44ec84b0d00</PolicyId>
<Status>Active</Status>
<TimeZoneId>USCentral</TimeZoneId>
</AbcDto>
当我尝试为Web Api创建自定义模型活页夹
When I am trying creating Custom Model Binder for Web Api
public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var json = actionContext.Request.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrEmpty(json))
{
var jsonObject = (JObject) Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var jsonPropertyNames = jsonObject.Properties().Select(p => p.Name).ToList();
作为参数传递给以下方法的json字符串是xml作为字符串我在Newtonsoft.Json.JsonConvert.DeserializeObject(json);中面临异常异常详细信息:解析值<时遇到意外字符.路径",第0行,位置0.
The json string passing as an parameter to the below method is an xml as stringI am facing exception at Newtonsoft.Json.JsonConvert.DeserializeObject(json);Exception Details:Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
推荐答案
由于 JsonConvert.DeserializeObject()
需要JSON输入,而不是XML.如果要使用 JObject
处理XML,您需要先将XML转换为JSON. JsonConvert
类具有 SerializeXmlNode()
方法.
You are getting an error because JsonConvert.DeserializeObject()
expects JSON input, not XML. If you want to handle XML with a JObject
, you'll need to convert the XML to JSON first. The JsonConvert
class has a SerializeXmlNode()
method for this purpose.
演示:
class Program
{
static void Main(string[] args)
{
string json = @"
<AbcDto xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Abc"">
<Id>2</Id>
<Description>sample string 4</Description>
<Name>sample string 3</Name>
<PolicyId>c17f5b9f-c9bf-4a3a-b09b-f44ec84b0d00</PolicyId>
<Status>Active</Status>
<TimeZoneId>USCentral</TimeZoneId>
</AbcDto>";
// If the json string contains XML, convert it to JSON
if (json.TrimStart().StartsWith("<"))
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(json);
json = JsonConvert.SerializeXmlNode(doc, Formatting.None, true);
}
// Now you can load the JSON into a JObject
var jsonObject = JObject.Parse(json);
var jsonPropertyNames = jsonObject.Properties().Select(p => p.Name).ToList();
foreach (string name in jsonPropertyNames)
{
Console.WriteLine(name);
}
}
}
输出:
@xmlns:i
@xmlns
Id
Description
Name
PolicyId
Status
TimeZoneId
这篇关于无法使用Newtonsoft.Json.JsonConvert.DeserializeObject反序列化xml字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!