Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

c#

xml

  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

like image 383
sudhir Avatar asked Mar 28 '26 01:03

sudhir


1 Answers

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

like image 82
I4V Avatar answered Mar 29 '26 15:03

I4V