我的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字符串中出现双引号是否有问题。
请帮帮我。
答案 0 :(得分:0)
使用Load()
方法,它将解决问题。 See more
,否则强>
doc.LoadXml(responsestring.Substring(responsestring.IndexOf(Environment.NewLine)));
答案 1 :(得分:0)
最后通过将字符串转换为steam并再次转换为字符串来获得解决方案:
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:How do I prevent ReadAsStringAsync returning a doubly escaped string?