0

I have a XML which I am converting to JSON and finally into C# Object.

Below is the XML <State Description="Georgia">GA</State>

which converts to Json as

"State": { "@Description": "Georgia", "#text": "GA" }

But if the XML is <State>GA</State>

then it is "State" : "GA"

Now the problem I am facing is to write the type while deserializing.

If I declare State as String it works for <State>GA</State> condition.

[JsonProperty("State")] public string State { get; set; }

for <State Description="Georgia">GA</State> the below declaration works. But how can I declare so that it works for both the condition , Since the Description is optional we may or may not get the value.

public State State { get; set; }

public partial class State
    {
        [JsonProperty("#text")]
        public string Text { get; set; }

        [JsonProperty("@Description")]
        public string Description { get; set; }
    }
amit agarwal
  • 83
  • 10
  • Easiest would be to create a [custom `JsonConverter`](https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm) for `State` like the one in [Best way to upgrade JSON field to a class structure](https://stackoverflow.com/a/65906515/3744182) that checks whether the incoming token is a string or object, and deserializes accordingly. Does that question answer yours also? – dbc Aug 11 '21 at 06:06
  • JsonConverter was the first thing I tried but couldn't achieve as per my requirement. If you could advise . – amit agarwal Aug 11 '21 at 06:09
  • 1
    Do it just like the one from [Best way to upgrade JSON field to a class structure](https://stackoverflow.com/a/65906515/3744182), except 1) Replace `Author` with `State`, and 2) for `JsonToken.String` return `new State { Text = (string) reader.Value }`. You can also get rid of the `UnityEngine.Debug.Log(ex);` catch/throw since that is debugging code specific to that question and doesn't apply to you. – dbc Aug 11 '21 at 06:11
  • Did that answer work for you? – dbc Aug 11 '21 at 14:18
  • 1
    Yes... I used the CustomConverter. – amit agarwal Aug 12 '21 at 07:02

0 Answers0