Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

c# - Force JsonConvert.SerializeXmlNode to serialize node value as an Integer or a Boolean

The SerializeXmlNode function from Newtonsoft.Json.JsonConvert class always outputs the value of the last child nodes of a XML as a string type in the serialization process, when sometimes you might need them to be serialized as an Integer or a Boolean.

Sample code:

<Object>
  <ID>12</ID>
  <Title>mytitle</Title>
  <Visible>false</Visible>
</Object>

Output:

{ "ID" : "12",
  "Title" : "mytitle",
  "Visible" : "false"
}

Desired output:

{ "ID" : 12,
  "Title" : "mytitle",
  "Visible" : false
}

Is there a way to force a XML node to be serialized as a Integer or a Boolean?

Thank you.

Note: Please avoid posting workarounds when the XML is already serialized to a JSON string, as those workarounds are the ones that we are willing to avoid.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JSON.NET is not a tool for XML serialization. It's serialization of XML nodes is meant to provide one-to-one correspondence between XML and JSON. As attributes in XML can be only of type string, type information is not preserved during the serialization. It will be useless when deserializing back to JSON.

If you need to convert XML to JSON, I suggest using a DTO class which supports both XML and JSON serialization.

[XmlRoot ("Object"), JsonObject]
public class Root
{
    [XmlElement, JsonProperty]
    public int Id { get; set; }

    [XmlElement, JsonProperty]
    public string Title { get; set; }

    [XmlElement, JsonProperty]
    public bool Visible { get; set; }
}

Deserialize from XML and then serialize to JSON:

public class Program
{
    private const string xml = @"
        <Object>
          <Id>12</Id>
          <Title>mytitle</Title>
          <Visible>false</Visible>
        </Object>";

    private static void Main ()
    {
        var serializer = new XmlSerializer(typeof(Root));
        var root = (Root)serializer.Deserialize(new StringReader(xml));
        Console.WriteLine(JsonConvert.SerializeObject(root, Formatting.Indented));
        Console.ReadKey();
    }
}

Output:

{
  "Id": 12,
  "Title": "mytitle",
  "Visible": false
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...