【问题标题】:How to process JSON to remove period from field names?如何处理 JSON 以从字段名称中删除句点?
【发布时间】:2016-01-07 00:13:50
【问题描述】:

作为this question 的后续行动,我无法弄清楚如何从 JSON 输入中的所有字段名称中删除句点。

我正在将 XML 转换为 JSON 并创建一个 BsonDocument 以使用 Newtonsoft 库插入到 MongoDB 数据库中,如下所示:

XmlDocument doc = new XmlDocument();
doc.Load(filePath);

String jsonText = JsonConvert.SerializeXmlNode(doc);

BsonDocument = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(jsonText);

我不能插入它,因为元素名称包含句点,我会得到一个序列化异常。如何通过 JSON 字符串或 BsonDocument 进行处理以更改它们?

我已经成功地递归地遍历了我的文档:

private void Print(BsonDocument document)
{
    foreach (BsonElement element in document)
    {
        Console.WriteLine(element.Name);

        if (element.Value.IsBsonDocument)
        {
            Print(element.Value.AsBsonDocument);
        }
        else if (element.Value.IsBsonArray)
        {
            var array = element.Value.AsBsonArray;
            foreach (BsonDocument doc in array)
            {
                Print(doc);
            }
        }
    }
}

但是,BsonDocument.Name 不是我可以设置的字段,只能获取。如何更新 BsonDocument 或 JSON 字符串以删除无效字段名称?

【问题讨论】:

    标签: c# json mongodb json.net


    【解决方案1】:

    我对您的 XML/JSON 结构了解不够,但您为什么不在将 XML 转换为 JSON 并替换 ElementNames 之前对其进行处理?如ANSWER中所述?

    XmlDocument xmlDoc = new XmlDocument();
    
            xmlDoc.LoadXml(File.ReadAllText(@"{path}\xml.xml", Encoding.Default));
    
            XmlNodeList nodeList = xmlDoc.SelectNodes("//*['.' = substring(name(), string-length(name())- string-length('.') +1)]");
    
            foreach (XmlNode node in nodeList)
            {
    
                string newName = node.Name.Replace(".", "");
                // create new (renamed) Content node
                XmlNode newNode = xmlDoc.CreateElement(newName);
    
                newNode.InnerXml = node.InnerXml;
    
                // replace existing BatteryTest node with newly renamed Content node
                node.ParentNode.InsertBefore(newNode, node);
                node.ParentNode.RemoveChild(node);
            }
    
            xmlDoc.Save(@"{path}\xml.xml");
    

    【讨论】:

    • 各位好伙伴,我只是提醒一下,因为有时人们会完全忘记它!
    • 是的哈哈,我给出的答案比我提出的问题还多,而且我经常看到。你所说的似乎会起作用,我不怀疑你,但我不想接受它,因为其他人可能会偶然发现这一点,以防我们需要稍微调整答案才能真正起作用。
    • 很高兴我能提供帮助 :) 我很确定你也会这样做。编码愉快!
    • 我必须说,你给我这个赏金真是太慷慨了!我帮助过很多人的方式就像我帮助你的方式,但从来没有人以你的方式回应过。
    • 嗯,我感觉很糟糕,只是因为需要时间,而且你做了大部分的腿部工作。如果您回答过一次并且很简单,我可能不会这样做,但我绝对感谢您抽出时间回来检查它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 2018-04-06
    • 1970-01-01
    相关资源
    最近更新 更多