XML String to JSON using only native .NET methods - c#

I'm trying to rewrite a php function to C#. The php function converts an XML string to JSON.
At first, I came up with this:
string[] zips = { "27249","27215"}; // Request.Form.Get("zip").ToArray();
List<string> listings = new List<string>();
var webClient = new WebClient();
for (int i = 0; i != zips.Length; i++)
{
string returnXml = webClient.DownloadString("http://gateway.moviefone.com/movies/pox/closesttheaters.xml?zip=" + zips[i]);
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(returnXml);
listings.Add(json);
Response.Write(json);
}
But the output included encoded characters, which wasn't what I wanted.
Then, using JSON.NET, I replaced the loop body with this:
string returnXml = webClient.DownloadString("http://gateway.moviefone.com/movies/pox/closesttheaters.xml?zip=" + zips[i]);
var xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(returnXml);
var json = JsonConvert.SerializeXmlNode(xmlDoc);
listings.Add(json);
What bothers me about this is thatthe conversion of the Xml string to an XmlDocument just so that I can convert it back to a JSON string seems unnecessary. I want the JSON string for later use in a jQuery function.
How can I make the first version work just using intrinsic .NET methods?
Thanks.

I can't tell you if there is a pre-made tool which does what you are looking for, but if you are looking to squeeze every bit of performance from this conversion, you can use JsonReader to read the JSON stream, and then use XmlWriter to output it to XML stream
With that said, if JSON you are getting comes from internet, you are unlikely going to significantly improve performance. But you are likely to introduce bugs. I would advice against that

Related

How do I format a one line JSON string

I'm creating a GUI in Visual Studio which is going to fetch JSON data from an API to display in a text box, and I want it to be displayed formatted so it's readable.
I have tried to use the Newtonsoft.Json library to solve the problem, but it seems like it does not work on one liners of JSON and must take an object containing different types of JSON data.
using (WebClient wc = new WebClient())
{
string API_Key = "000000000000000000000"; // URL with API key containing the JSON data
string JSON_Data_URL = $"https://www.nobil.no/api/server/datadump.php?apikey={API_Key}&countrycode=NOR&fromdate=2005-01-01&format=json";
LoadJSON.Increment(-100); // Reset loadbar
string JSON_Data = JsonConvert.SerializeObject(wc.DownloadString(JSON_Data_URL), Formatting.Indented); // Format JSON data
DataResults.Text = JSON_Data; // Add JSON data to textbox
LoadJSON.Increment(100); // Display when the JSON data is fetched
}
I thought it would output an formatted JSON string, but seems like it instead is just adding backslashes to the JSON. I also tried to replace the backslashes with a new line and 4 spaces, but that didn't look right either.
Edit
This is not a duplicate as the problem seemed to be that I needed to convert the string to an object.
The problem is, that you are serializing a string and not an object.
string JSON_Data = "..." // Get your json from your API
object JSON_Object = JsonConvert.DeserializeObject(JSON_Data);
string JSON_Data_Formatted = JsonConvert.SerializeObject(JSON_Object, Formatting.Indented);

string being appened to json output

I am trying to use json.net to produce a web service but I am a bit perplexed as to why < string > is showing in the dummy data
[WebMethod]
public string getCustomerInfo(string IVACode)
{
var customerData = _dal.apertureAppstblCustomers.Where(a => a.IVACode == IVACode).ToList();
var jsonstring = JsonConvert.SerializeObject(customerData);
return jsonstring;
}
ie its starting like <string> and ending </string> how do i get it to display CustomerInformationinstead of string is it good practise to be naming the nodes?.
[{"id":"7aee450a-a9a7-4f19-83d3-467a3b8a39c0","IVACode":"IVA002","FirstName":"Peter","LastName":"Carson","AddressLine1":"Waters Edge Belfast","AddressLine2":null,"Town":"Belfast","County":"Down","PostCode":"BT99YXX","Telephone":null,"EmailAddress":"email","isActive":true,"authUserName":null,"authCreatedDate":null,"personalProgressValue":null,"contributionsToDate":null,"totalContributions":null,"totalArrears":50000.00,"totalPaid":null,"isDeleted":false,"deviceId":null,"deviceOs":null}]
You will need to convert the serialized string back to your object and then consume it to show the relevant information.
Example below.
JsonConvert.DeserializeObject(jsonstring)
You shouldn't get that in the serialized string but you can replace those tokens using Replace() string function like
jsonstring = jsonstring.Replace("<string>","").Replace("</string>","");

Remove dynamic substring from string c#

I am currently implementing a system and came across the following problem.
We are making a call to a 3rd party supplier that provides a string of contents which is not in JSON format, therefore we are trying to remove content from the string, in order to build a JSON string and serialize it into our own object.
We are trying to remove the part from {"imgCount to ]", (just before the "images":
An example of the string is the following:
img_CB("imgCount":31,"imgHash":"[6ede94341e1ba423ccc2d4cfd27b9760]","images":{...});
The issue is that, the imgCount and imgHash may not be in that order. It could be in something like the following:
img_CB("images":{....}, "imgHash":"[6ede94341e1ba423ccc2d4cfd27b9760]", "imgCount":31);
Therefore this makes it quite dynamic and hard to determine where to start "replacing" from.
Would anyone help to possibly build a regex expression to replace/remove the imgHash and imgCount tags with their values please?
Thanks
Looks like you're getting a jsonp response. Have a look at this answer on how to parse your json after stripping off the jsonp stuff:
How to parse JSONP using JSON.NET?
Example:
string supposedToBeJson = "img_CB(\"imgCount\":31,\"imgHash\":\"[6ede94341e1ba423ccc2d4cfd27b9760]\",\"images\":{});";
var jobject = JObject.Parse(supposedToBeJson.Replace("img_CB(", "{").Replace(");", "}"));
var images = jobject.SelectToken("images");
try this:
str = Regex.Replace(str, "\"imgCount*,","");
str = Regex.Replace(str, "\"imgHash*,","");
str = Regex.Replace(str, ",*\"imgCount*)",")");
str = Regex.Replace(str, ",*\"imgHash*)",")");

JSON string failing in JSON.parse but passes JsonConvert.DeserializeObject

My C# class is
public class Man
{
public string name {get; set;}
}
String to deserialize is like this
var content = "[{name: \"john\"}]"
Now before saving to db, I was doing check that if string can be deserialized to C# object then store it. This check passes
JsonConvert.DeserializeObject<List<Man>>(content)
So I save this string in db but when I do JSON.parse over saved string in javascript, it crashes with error
JSON.parse("[{name: \"john\"}]")
SyntaxError: Unexpected token n
Now I understand that by surrounding quotes around key ("name") this can be solved. This is correct string that works in both JSON.parse and JsonConvert.DeserializeObject
var content = "[{\"name\": \"john\"}]
Problem is I have many such ill formed strings in db already that crash on JSON.parse only. What is the best way to convert such strings so that JSON.parse will work? Something better than string.replace
Please note that actual strings are quite big and complicated compared to example given.
You can use the using Newtonsoft.Json; it will DeserializeObject object even your json data in var content = "[{name: \"john\"}]" format.
value contains data like :{StyleId:"1710","SelectedItemToColorMap":{1391:"583",21531:"7733"}}
var jsondata = JsonConvert.DeserializeObject(value);
after DeserializeObject the jsondata look like
{
"StyleId": "1710",
"SelectedItemToColorMap": {
"1391": "583",
"21531": "7733"
}
}

Convert JSON String to XML string

I have a JSON string as :
var jsonString = JSON.stringify(dataObject);
document.getElementById("hdnChromedata").value = jsonString;
==> hdnChromedata = JSON string
BUT in a different code section I am storing XML serialized string to "hdnChromedata" .as :
XmlSerializer xmlSerializer = new XmlSerializer(vinDescription.GetType());
StringWriter textWriter = new StringWriter();
xmlSerializer.Serialize(textWriter, vinDescription);
this.hdnChromedata.Value = textWriter.ToString();
==> hdnChromedata = XML string
AND while retriving the values I am deserializing the string like this :
XmlDocument doc = new XmlDocument();
doc.LoadXml(this.hdnChromedata.Value);
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
XmlSerializer ser = new XmlSerializer(decodedInfo.GetType());
object textObj = ser.Deserialize(reader);
vinDescription = (AutoExact.AEVINDecoderService.VINDescription)textObj;
HERE the line doc.LoadXml(this.hdnChromedata.Value)
is throwing error when hdnChromedata is a JSON string.
My question is, HOW can I make this JSON String to XML string?
OR is there any other to address this?
Basically I need a method to convert JSON string to XML string in ASP.NET 1.1
You can use the Json.NET library's JsonConvert for that. See the specifics at http://james.newtonking.com/projects/json/help/index.html?topic=html/ConvertingJSONandXML.htm.
Json.NET is an open-source JSON handling library for .NET, and it's the best there is.
No need for conversion, just test the first character of the string before deserialising it. If the string starts with <, then treat it as XML, and if it starts with {, then treat it as JSON.
Use json-lib, a library which adds JSON support to any Java program. json-lib provides an XMLSerializer which can be used to output XML from a JSON object.
https://discursive.atlassian.net/wiki/display/CJCOOK/Converting+JSON+to+XML

Categories