【问题标题】:Unable to parse JSON response string to XML无法将 JSON 响应字符串解析为 XML
【发布时间】: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


    【解决方案1】:

    改用Load() 方法,它会解决问题。 See more

    否则

    doc.LoadXml(responsestring.Substring(responsestring.IndexOf(Environment.NewLine)));
    

    Live Demo

    【讨论】:

    • 我已经尝试过了,但都给出了错误:.Load() 给出了 --- >路径中的非法字符。并且 responsestring.Substring(responsestring.IndexOf(Environment.NewLine) 给出 ----> {"StartIndex 不能小于零。\r\n参数名称:startIndex"}
    • 在加载时在 xml 之前使用 @。
    • 在我传递给 .Load() 的 xml 字符串之前?
    【解决方案2】:

    终于得到了解决办法,把字符串转成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);
    

    在此之后,我找到了这个非常适合的解决方案: 发帖:How do I prevent ReadAsStringAsync returning a doubly escaped string?

    【讨论】:

      猜你喜欢
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 2017-07-28
      • 2018-06-02
      • 2017-03-24
      • 1970-01-01
      相关资源
      最近更新 更多