tags:

views:

713

answers:

1

I have a question regarding the JSON.Net library. Normally I have a XML string like this:

<Config>
  ....
  <Name>some name</Name>
  ....
</Config>

Then I use JSON.Net library to transform the string to a json string like this:

Congif: {
   ...
   Name: "some name",
   ...
}

Finally I map this json string to an instance of Config class:

Config instance = JsonConvert.DeserializeObject<Config>(json);

If the name property is an array of names in my Config class:

class Config {
   ....
   public string[] Name { get; set; }
   ....
}

I understand that in json string an array is defined like this:

  Name: ["some name"],

Since I get a json string converted from an XMl string, I may have one or more Name nodes there. This cause me trouble when only one Name is defined in the XMl. I'll get exception complaining that it cannot convert string to string[]. It will be OK if more than one Name nodes are defined in the XML file.

Not sure if there is any way or option seettings to let JSON library to convert it to an array of strings automatically when the mapping sees the target property Name is an array type property even there is only one value of Name?

A: 

I think I have to accept the way JSON.Net way. If an jsonString contains a string value for a key, then it should convert the value to a a string value instead of array of strings, even the mapping property is an array type.

What I can do is to add an empty value node to XML string to make it like array of nodes if there is only one node in the XML string, or add empty value node to all the existing nodes regardless.

The only problem is that an empty entry is appended the array.

David.Chu.ca