2

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. That's not quite what I'm asking about. I have JSON already. The JSON contains XML, as shown in the question. I am calling the native JsonConvert.DeserializeObject function on that JSON object, and the exception I noted is what comes back. JsonConvert.SerializeObject works on this class.
@dodexahedron What is not clear? There is no built-in way to do what you want. If you need this, you'll have to implement your JsonConverter class (two methods, one line of code each). Then either pass converter to DeserializeObject method or decorate properties in your object with your converter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.