首页 > 解决方案 > 我需要序列化包含xml的json文件

问题描述

我有 JSON,我需要反序列化它。Json 文件在里面包含 XML。有什么建议么?

{"nt":0,"r":true,"o":[{"test":"20fgfgdfgdfAZ20AIgdg151","fddf":"ZregrIPgdffgfSgfg","d":"<DataPDU xmlns="urn:cma:stp:xsd:stp.1.0">
<Body>
</AppHdr>
<Document xmlns="urn:iso:">  
      ..... 
    </Document></Body>
</DataPDU>"}]}

标签: c#.netjsonxmlasp.net-core

解决方案


您的 JSON 字符串似乎无效。o[0].d您在、 或 XML 部分中有未转义的引号。我在下面提供了带有转义引号的 JSON 版本。

{
    "nt": 0,
    "r": true,
    "o": [
         {
            "test": "20fgfgdfgdfAZ20AIgdg151",
            "fddf": "ZregrIPgdffgfSgfg",
            "d": "<DataPDU xmlns=\"urn:cma:stp:xsd:stp.1.0\"><Body></<Document xmlns=\"urn:iso:\">  ..... </Document></Body></DataPDU>"
         }
     ]
}

使用 .NET Core 3.1 和System.Text.Json命名空间,您可以使用以下内容反序列化上述 json:

async Task Main()
{
    string fileName = "ExampleJson.txt";
    Example example = null;

    using (FileStream fs = File.OpenRead(fileName))
    {
        example = await JsonSerializer.DeserializeAsync<Example>(fs);
    }
}

System.Text.Json可以在此处找到有关使用命名空间的文档。


推荐阅读