sudhir
sudhir

Reputation: 320

how to validate JSON string before converting to XML in C#

  1. I will receive an response in the form of JSON string.
  2. We have an existing tool developed in C# which will take input in XML format.
  3. Hence i am converting the JSON string obtained from server using Newtonsoft.JSON to XML string and passing to the tool.

Problem: When converting JSON response to XML, I am getting an error

"Failed to process request. Reason: The ' ' character, hexadecimal value 0x20, cannot be included in a name."

The above error indicates that the JSON Key contains a space [For Example: \"POI Items\":[{\"lat\":{\"value\":\"00\"}] which cannot be converted to XML element.

Is there any approach to identify spaces only JSON key's ["POI Items"] and remove the spaces in it?

Also suggest any alternative solution so that we needn't change the existing solution?

Regards,
Sudhir

Upvotes: 3

Views: 2784

Answers (2)

I4V
I4V

Reputation: 35353

You can use Json.Net and replace the names while loading the json..

JsonSerializer ser = new JsonSerializer();
var jObj = ser.Deserialize(new JReader(new StringReader(json))) as JObject;

var newJson = jObj.ToString(Newtonsoft.Json.Formatting.None);

.

public class JReader : Newtonsoft.Json.JsonTextReader
{
    public JReader(TextReader r) : base(r)
    {
    }

    public override bool Read()
    {
        bool b = base.Read();
        if (base.CurrentState == State.Property && ((string)base.Value).Contains(' '))
        {
            base.SetToken(JsonToken.PropertyName,((string)base.Value).Replace(" ", "_"));
        }
        return b;
    }
}

Input : {"POI Items":[{"lat":{"value":"00","ab cd":"de fg"}}]}

Output: {"POI_Items":[{"lat":{"value":"00","ab_cd":"de fg"}}]}

Upvotes: 8

Gábor Imre
Gábor Imre

Reputation: 6299

I recommend using some sort of Regex.Replace().
Search the input string for something like:

\"([a-zA-Z0-9]+) ([a-zA-Z0-9]+)\":

and then replace something like (mind the missing space):

\"(1)(2)\":

The 1st pair of parenthesis contain the first word in a variable name, the 2nd pair of parenthesis means the 2nd word. The : guarantees that this operation will be done in variable names only (not in string data). the JSON variable names are inside a pair of \"s.

Maybe it's not 100% correct but you can start searching by this. For details check MSDN, and some Regex examples
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx

Upvotes: -2

Related Questions