3
  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

2 Answers 2

8

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"}}]}

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

2 Comments

Shouldnt the cd":"de fg" be converted to cd":"de_fg" as well?
@GeorgeNikolaides No, as asked in question Is there any approach to identify spaces only JSON key's ["POI Items"] and remove the spaces in it?
-2

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

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.