【问题标题】:I need to serialize json file which includes xml inside我需要序列化包含xml的json文件
【发布时间】:2020-07-09 09:43:18
【问题描述】:

我有 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>"}]}

【问题讨论】:

  • xml 基本上都是一个字符串。您是否尝试过先反序列化 Json,然后再分别反序列化 XML?
  • 我试图反序列化为一个对象,但它抛出了一个异常
  • 这将有助于向我们展示您尝试过的内容以及确切的错误,以便能够提供更好的答案:)
  • 我尝试创建一个模型来反序列化 JSON。但是这个 XML 文件结构不会是一样的,每次 XML 结构都在变化。这是我的问题)
  • 当我尝试使用在线转换器作为 JSON2C# 创建对象时,它显示无效 JSON 语法

标签: c# .net json xml asp.net-core


【解决方案1】:

您的 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 命名空间的文档可以在here 找到。

【讨论】:

    【解决方案2】:

    请注意," 必须在您的 xml-STRING 中更改为 \",请理解代码不起作用。 ;)

    using System.Text.Json;
    public myJson()
    {
        string json = "<json>";
        Rootobject jsonObject = JsonConvert.DeserializeObject<Rootobject>(json);
    }
    public class Rootobject
    {
        public int nt { get; set; }
        public bool r { get; set; }
        public O[] o { get; set; }
    }
    
    public class O
    {
        public string test { get; set; }
        public string fddf { get; set; }
        public string d { get; set; }
    }
    

    【讨论】:

    • 我无法使用 string.Replace() 方法将“更改为 \”。您能提出一些建议吗?
    • 是的。有一种方法可以做到这一点,但是当或多或少会有空白时,它不会正常运行。有没有办法替换那些“
    猜你喜欢
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 2015-10-06
    相关资源
    最近更新 更多