如何处理JSON以从字段名称中删除句点?

时间:2015-12-28 13:27:48

标签: c# json mongodb json.net

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

我正在使用Newtonsoft库将XML转换为JSON并创建一个BsonDocument插入到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字符串以删除无效的字段名称?

1 个答案:

答案 0 :(得分:2)

我对XML / JSON结构知之甚少,但为什么在将XML转换为JSON并替换ElementNames之前不处理XML?如此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");