【发布时间】:2016-07-25 10:27:18
【问题描述】:
我的 Web 服务正在使用对象将格式化为 XML 的 json 字符串提供给 XMl 序列化程序。我的回答是:
public static string ObjectToXmlString(this Object obj)
{
string xmlStr = string.Empty;
XmlSerializer xs = new XmlSerializer(obj.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
using (MemoryStream memoryStream = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings()
{
Encoding = Encoding.UTF8,
Indent = false,
OmitXmlDeclaration = true,
NewLineChars = string.Empty,
NewLineHandling = NewLineHandling.None
};
using (XmlWriter writer = XmlWriter.Create(memoryStream, settings))
{
xs.Serialize(writer, obj,ns);
}
return Encoding.UTF8.GetString(memoryStream.ToArray()).Replace("\"", string.Empty);
}
}
服务响应:
"<ArrayOfOwnerShipDetails><OwnerShipDetails><OwnerShipId>80932</OwnerShipId><FileNumber>rp1144</FileNumber><Salutation>Mr</Salutation><OwnerFirstName>Jai Kumar Datwni ji</OwnerFirstName><OwnerMiddleName /><OwnerLastName /><ResidentialAddress>1159 Sec 18 C,c Hd</ResidentialAddress><EmailID /><MobileNumber /><VoterID /><AadharCardNo /><RelationCode>S</RelationCode><RelationDescription>Son of</RelationDescription><FatherOrHusbandName>Lachman Dass S</FatherOrHusbandName><PropertyShareInPercentage>50.00</PropertyShareInPercentage><AdditionalRemarks /></OwnerShipDetails></ArrayOfOwnerShipDetails>"
但是当我尝试将此 json 响应解析到我正在调用我的服务的其他应用程序时。
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
var response = client.GetAsync("http://localhost:50429/api/Haris/GetOwnersByFileNo?fileNo=RP1144").Result;
if (response.IsSuccessStatusCode)
{
// by calling .Result you are performing a synchronous call
var responseContent = response.Content;
// by calling .Result you are synchronously reading the result
string responseString = responseContent.ReadAsStringAsync().Result.Trim();
// Create the XmlDocument.
XmlDocument doc = new XmlDocument();
**doc.LoadXml(responseString ); ---> Error Comes here**
}
}
它给出了错误 根级别的数据无效。第 1 行,位置 1
但是,如果我将相同的响应复制到记事本,然后在运行时粘贴到变量,它就可以正常工作。 json字符串中的双引号有什么问题吗?
请帮帮我。
【问题讨论】:
标签: c# .net json xml asp.net-web-api