3

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?

1
  • I am struggling with the same issue. :-( Commented Dec 9, 2009 at 15:15

1 Answer 1

1

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.

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

Comments

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.