简体   繁体   English

使用JsonConvert.SerializeObject的json.net在输出中添加注释

[英]json.net using JsonConvert.SerializeObject adds a comment to output

How do I remove the comment at the bottom of created json string? 如何删除创建的json字符串底部的注释?

I am attempting to use Json.net to convert xml to json. 我正在尝试使用Json.net将xml转换为json。 Specifically, I am fetching data from the Zillow API which returns XML which I need to deliver to a web browser as a json string. 具体来说,我是从Zillow API获取数据的,该API返回XML,我需要将其作为json字符串传递到Web浏览器。 Thanks to questions/answers found on this site, I have been able to use json.net in my c# page to maket the conversion, BUT... 多亏了在此站点上找到的问题/答案,我才能够在c#页面中使用json.net进行转换,但是...

I use the following to convert my xml to json: 我使用以下内容将xml转换为json:

public String GetJson(XmlDocument xml)
{
    return Newtonsoft.Json.JsonConvert.SerializeObject(xml);
}

I successfully get a json formatted String, but this comment is added at the bottom of the json (seems to be a timestamp). 我成功获取了json格式的String,但是此注释已添加到json的底部(似乎是时间戳记)。

{
... json-formatted output...
/* H:011  T:134ms  S:1206  R:Tue May 02 07:59:03 PDT 2017  B:5.0.42642-master.3acb9f9~hotfix_pre.b72ccda */
}

I have checked the original xml to verify the comment is not there, so I have concluded it is added by json.net. 我已经检查了原始的xml以确认注释不存在,因此我得出结论说它是由json.net添加的。 I have searched this site - and Google - for info on this, but I am not finding the right search tokens to find any mention of this comment. 我已经在这个网站(和Google)上搜索了有关此信息,但是我找不到合适的搜索标记来找到对此评论的任何提及。

Thanks! 谢谢!

There is no way that Json.NET will insert a hardcoded comment when serializing an XmlDocument -- there simply isn't any logic to do this in XmlNodeConverter . 序列化XmlDocument时,Json.NET不可能插入硬编码的注释 XmlNodeConverter根本没有任何逻辑可以做到这XmlNodeConverter The only time XmlNodeConverter will write a comment is if an XML node of type XmlNodeType.Comment was actually encountered in the XML DOM hierarchy, at around line 1502 in the source code: XmlNodeConverter唯一要写注释的时间是,如果在XML DOM层次结构中实际上遇到了XmlNodeType.Comment类型的XML节点,则在源代码的第1502行处:

            case XmlNodeType.Comment:
                if (writePropertyName)
                {
                    writer.WriteComment(node.Value);
                }
                break;

Thus there are only a few ways such a comment string could have gotten added to your JSON output, including: 因此,仅有几种方法可以将这样的注释字符串添加到您的JSON输出中,包括:

  1. There might actually be comments in your XML, added by the Zillow API or by your own app somewhere in its code stack. Zillow API或您自己的应用程序在其代码堆栈中的某些地方,实际上可能在XML中添加了注释 For instance, given the following XML: 例如,给定以下XML:

     <?xml version="1.0" encoding="utf-8" ?> <root> <childNode> <innerChildNode>Some Text</innerChildNode> </childNode> <!-- H:011 T:134ms S:1206 R:Tue May 02 07:59:03 PDT 2017 B:5.0.42642-master.3acb9f9~hotfix_pre.b72ccda --> </root> <!-- H:011 T:134ms S:1206 R:Tue May 02 07:59:03 PDT 2017 B:5.0.42642-master.3acb9f9~hotfix_pre.b72ccda --> 

    Json.NET will generate the following JSON: Json.NET将生成以下JSON:

     { "?xml": { "@version": "1.0", "@encoding": "utf-8" }, "root": { "childNode": { "innerChildNode": "Some Text" }/* H:011 T:134ms S:1206 R:Tue May 02 07:59:03 PDT 2017 B:5.0.42642-master.3acb9f9~hotfix_pre.b72ccda */ }/* H:011 T:134ms S:1206 R:Tue May 02 07:59:03 PDT 2017 B:5.0.42642-master.3acb9f9~hotfix_pre.b72ccda */ } 
  2. Somewhere in your code stack, your app might have installed its own version of XmlNodeConverter in JsonConvert.DefaultSettings that inserts comments into the output. 在代码堆栈中的某个位置,您的应用程序可能已在JsonConvert.DefaultSettings中安装了自己的XmlNodeConverter版本,该版本XmlNodeConverter注释插入到输出中。 For instance, given the following global converter: 例如,给定以下全局转换器:

     JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Converters = { new FixedXmlNodeConverter() }, }; public class FixedXmlNodeConverter : Newtonsoft.Json.Converters.XmlNodeConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { base.WriteJson(writer, value, serializer); writer.WriteComment("Global Comment: H:011 T:134ms S:1206 R:Tue May 02 07:59:03 PDT 2017 B:5.0.42642-master.3acb9f9~hotfix_pre.b72ccda"); } } 

    The JSON generated will contain extra comments: 生成的JSON将包含额外的注释:

     { "?xml": { "@version": "1.0", "@encoding": "utf-8" }, "root": { "childNode": { "innerChildNode": "Some Text" }/* H:011 T:134ms S:1206 R:Tue May 02 07:59:03 PDT 2017 B:5.0.42642-master.3acb9f9~hotfix_pre.b72ccda */ }/* H:011 T:134ms S:1206 R:Tue May 02 07:59:03 PDT 2017 B:5.0.42642-master.3acb9f9~hotfix_pre.b72ccda */ }/*Global Comment: H:011 T:134ms S:1206 R:Tue May 02 07:59:03 PDT 2017 B:5.0.42642-master.3acb9f9~hotfix_pre.b72ccda*/ 
  3. You might be using your own custom build of Json.NET with a customized version of XmlNodeConverter . 您可能正在使用自己的Json.NET定制版本和XmlNodeConverter的定制版本。

Sample fiddle demonstrating the first two possibilities. 示例小提琴演示了前两种可能性。

If you actually have comment nodes in your XML, you can strip them by following one of the suggestions in How to remove all comment tags from XmlDocument or any number of similar questions. 如果您的XML中确实有注释节点,则可以按照如何从XmlDocument删除所有注释标签中的建议之一或其他类似问题来除去它们 If you have a global converter installed, you can supersede it by manually allocating an XmlNodeConverter and passing it to JsonConvert.SerializeObject() . 如果安装了全局转换器,则可以通过手动分配XmlNodeConverter并将其传递给JsonConvert.SerializeObject()来替代它。

To handle these two cases, your GetJson() might become: 要处理这两种情况,您的GetJson()可能变为:

    public String GetJson(XmlDocument xml)
    {
        XmlNodeList list = xml.SelectNodes("//comment()");
        foreach(XmlNode node in list)
        {
            node.ParentNode.RemoveChild(node);
        }

        var converter = new Newtonsoft.Json.Converters.XmlNodeConverter();
        // Use Newtonsoft.Json.Formatting.None in your production code
        return Newtonsoft.Json.JsonConvert.SerializeObject(xml, Newtonsoft.Json.Formatting.Indented, converter);
    }       

Sample fiddle . 样品提琴

If you are using your own custom build of Json.NET, you would need to investigate and fix why this is happening. 如果您使用自己的自定义版本的Json.NET,则需要调查并修复发生这种情况的原因。

If for whatever reason you cannot modify the incoming XmlDocument (or cannot fix your custom build of Json.NET) you could subclass JsonTextWriter and override WriteComment (and possibly WriteCommentAsync though that's not needed here) and make them do nothing: 如果因任何原因,你不能修改传入XmlDocument (或不能修复Json.NET的定制版本),你可以继承JsonTextWriter和覆盖WriteComment (也可能是WriteCommentAsync虽然我们在这里不会需要),并让他们做什么:

public class NoCommentJsonTextWriter : JsonTextWriter
{
    public NoCommentJsonTextWriter(TextWriter writer)
        : base(writer)
    {
    }

    public override void WriteComment(string text)
    {
    }
}

Then use it as follows: 然后按以下方式使用它:

    public String GetJson(XmlDocument xml)
    {
        var sb = new StringBuilder();
        using (var textWriter = new StringWriter(sb))
        // Use Newtonsoft.Json.Formatting.None in your production code
        using (var writer = new NoCommentJsonTextWriter(textWriter) { Formatting = Newtonsoft.Json.Formatting.Indented })
        {
            JsonSerializer.CreateDefault().Serialize(writer, xml);
        }
        return sb.ToString();
    }       

Sample fiddle . 样品提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Json.Net JsonConvert.SerializeObject json不正确 - Json.Net JsonConvert.SerializeObject json not correct 使用 JSON.net(JsonConvert.SerializeObject 或 JsonConvert.DeSerializeObject)为缺少的复杂属性设置默认值 - Set Default value for missing Complex properties with JSON.net (JsonConvert.SerializeObject or JsonConvert.DeSerializeObject) JSon.Net JObject.FromObject Vs JsonConvert.DeserializeObject <JObject>(JsonConvert.SerializeObject(obj)); - JSon.Net JObject.FromObject Vs JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(obj)); 使用JsonConvert.SerializeObject创建Json结构 - Create Json structure using JsonConvert.SerializeObject JsonConvert.SerializeObject添加默认结果名称 - JsonConvert.SerializeObject adds default Result name JsonConvert.SerializeObject 添加 \\r\\n - JsonConvert.SerializeObject adds \r\n 使用JsonConvert.SerializeObject C#时JSON结果中的问题 - Issue In JSON Result when using JsonConvert.SerializeObject C# JsonConvert.SerializeObject与json_encode - JsonConvert.SerializeObject vs json_encode JsonConvert.SerializeObject(本); 在JSON中呈现函数的结果 - JsonConvert.SerializeObject(this); to render the results of a function in the JSON JsonConvert.SerializeObject()导致JSON格式错误 - JsonConvert.SerializeObject() causing JSON to be malformed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM