简体   繁体   中英

JSON.Net deserialize object containing xml

I have a JSON object with a specific field whose value is always XML, as follows:

{
    ...
    "XmlValue": "<tag1><etc></etc></tag1>"
    ...
}

I'm using JSON.Net as the deserializer. I want to make this deserialize to a class like this:

public class ObjectContainingXml
{
    ...
    public XElement XmlValue { get;set; }
    ...
}

When I try, using JsonConvert.DeserializeObject<ObjectContainingXml>(input) , I get this exception: XmlNodeConverter can only convert JSON that begins with an object.

Is there a way to make this natively work in JSON.Net without treating that field as a string and then parsing the field to XML manually?

There's currently no built-in way to perform that kind of deserialization with JSON.Net.

Background:

XmlNodeConverter is meant to serialize XML as JSON. For example, a node like

<root><p>Text1<span>Span1</span> <span>Span2</span> Text2</p></root>

will be serialized as

{"root":{"p":{"#text":["Text1"," Text2"],"span":["Span1","Span2"]}}}

If you need XML to be serialized to string and back, you'll need to implement a custom JsonConverter .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM