Click here to Skip to main content
15,883,787 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am facing a problem when converting a JSON string to XML as there are white spaces in the names.I am getting the JSON dynamically..so cannot change the element names.Is there a way to remove the whitespaces from the element names or replace the white space with an '_'

Please provide a solution. Sample JSON string provided below :
JavaScript
[{"Team":"Customer Target & Solution",
	"SubTeam":"MDS",
	"Location":"Hyderabad",
"NBKID":"NBKQY0T",
"AssociateName":"Test1",
"Communication":null,
"Development":"85",
"KT Effort":"7",
"Production Support":"64",
"Project Related Training":"4",
"Release Support":null,
"Admin Support":null,
"Community Service":null,
"Leave":null,
"Non-Project Related KT":null,
"Non-Project Related Training":null,
"Other Activity":null,
"Project Utilization":"100.00",
"Gross Utilization":"100.00",
"id":null},
{"Team":"Customer Target & Solution",
"SubTeam":"TLS",
"Location":"Guragon",
"NBKID":"NBKUVKV",
"AssociateName":"Test2",
"Communication":"11",
"Development":"68",
"KT Effort":null,
"Production Support":"64",
"Project Related Training":null,
"Release Support":null,
"Admin Support":null,
"Community Service":null,
"Leave":"16",
"Non-Project Related KT":null,
"Non-Project Related Training":null,
"Other Activity":null,
"Project Utilization":"99.31",
"Gross Utilization":"99.31",
"id":null}]
Posted
v3
Comments
Jameel VM 31-Jul-13 3:25am    
from where you create the json string?
nanee 31-Jul-13 4:02am    
I get the string from a hidden value.
walterhevedeich 31-Jul-13 3:45am    
What language? The solution would depend on what programming language you are using.
nanee 31-Jul-13 4:03am    
I am using c#.Net
walterhevedeich 31-Jul-13 4:42am    
Are you by chance using Json.NET or are you using a different API?

1 solution

I guess there's no other way to modify the white spaces on the JsonObject than to iterate on each node. You can probably do something like below. Although your JSON string is different from the example, the idea is pretty much the same.
string jsonString = "{nodes:[{'Node 1':'value1','Node 2':'value2'}]}";

JObject jsonObject = JObject.Parse(jsonString);
JObject newJsonObject = new JObject();
JProperty property;
foreach(var token in jsonObject["nodes"].Values()){
    property = (JProperty)token;
    newJsonObject.Add(property.Name.Replace(" ", "_"), property.Value);
}
var xml = (XmlDocument)JsonConvert.DeserializeXmlNode(newJsonObject.ToString(),"root");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900