无法将JSON响应字符串解析为XML
本文关键字:XML 字符串 响应 JSON | 更新日期: 2023-09-27 17:58:37
我的web服务正在使用对象到XML序列化程序提供格式化为XML的json字符串。我的回答是:
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字符串中的双引号有什么问题吗。
请帮帮我。
改为使用Load()
方法,它将解决问题。查看更多
否则
doc.LoadXml(responsestring.Substring(responsestring.IndexOf(Environment.NewLine)));
实时演示
通过将字符串转换为蒸汽并再次转换为字符串,最终得到了解决方案:
string sb = responseString;
sb = responseString.Replace("'"", string.Empty).Trim().ToString().Trim();
var a = GenerateStreamFromString(sb);
StreamReader reader = new StreamReader(a);
string text = reader.ReadToEnd();
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseString);
在这之后,我找到了这个解决方案,它非常适合:POST:如何防止ReadAsStringAsync返回双转义字符串?