how to validate JSON string before converting to XML in C#
c#, json, xml
Solution
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"}}]}`
Problem
- I will receive an response in the form of JSON string. - We have an existing tool developed in C# which will take input in XML format. - 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