Custom Json serialization - c#

I have a list of KeyPairValue wich I serialize in Json Object using JavaScriptSerializer. The output of this operation give me something like this :
[{"Key":"A","Value":"ValueA"},{"Key":"D","Value":"ValueD"}]
I'ld like to get rid of those "" around the property name so it could look like this :
[{ Key:"A", Value:"ValueA"},{ Key:"D", Value:"ValueD"}]
Is there a way to achieve this or if what i'm looking for is just not a Json serialization ?

You can achieve it with Json.Net
StringWriter str = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(str);
writer.QuoteName = false; //<-- This is the trick
JsonSerializer jsonSer = new JsonSerializer();
jsonSer.Serialize(writer, new { ID = 1, Name = "Jack" });
string jsonstr = str.ToString();
Output is {ID:1,Name:"Jack"}

As I know it is a must requirement by JSON to embedd your keys in "". This is because JSON is actually a transport format for JavaScript objects and therefore it has some specifics.

The RFC specifies that a name is a string, and it also specifies that a string must be wrapped in quotation marks.
RFC 4627
It's worth noting the different types that values can be and that some of the types don't have to be wrapped in quotes. You can find this in the spec as well.

Related

Convert string into a valid JSON in c#

In the code snippet below, the JSON string in the commented out jsonString variable is valid while the uncommented out one causes JObject.Parse to throw a JsonReaderException with the message:
After parsing a value an unexpected character was encountered: e. Path 'Key', line 1, position 15.
var jsonString = "{\"Key\":\"Value \"extra\" \"}";
//var jsonString = "{\"Key\":\"Value \\\"extra\\\" \"}";
JObject.Parse(jsonString);
Are there any methods available in Newtonsoft.Json or elsewhere that can transform a JSON string to make it valid?
No, because NewtonSoft cannot guess what you want. E.g. is extra a new key and did you just ommit a comma or is it part of the previous value, or is it just something that can be ignored. It would be better to have the thing you are consuming the json from construct valid json.
Using Regex might help you to resolve the existing JSON you have. If you can control how subsequent JSON is generated, you really should fix it at that point.
This solution counts the value as existing from the first " after a "key":, through to the last " before a , or a }, and then it reserializes the value to ensure that it is correctly escaped. If it finds ",, it expects it to be followed by another key ("key":). This is in an attempt to avoid red herrings (i.e. {"key": "test "," value"}) which might otherwise confuse it.
private static string FixJson(string json)
{
var regex = new Regex("\"(?<key>.*?)\"\\W?:\\W?\"(?<value>.*?)\"(?=,\".*?\"\\W?:|}$)");
return regex.Replace(json, new MatchEvaluator(m => {
var key = m.Groups["key"].Value;
var val = m.Groups["value"].Value;
return string.Format("\"{0}\":{1}", key, JsonConvert.SerializeObject(val));
}));
}
Disclaimer: It's a regular expression, it's not foolproof, and if your JSON is more broken than you have indicated, it will probably spit out broken JSON, or incorrect values, so use it at your own risk.
Try it online

Cast string representation to Json

I have a string in this representation
{
transaction_id = 120,
transaction_shortname = 120. AUTO
}
It is not a Json representation i want to know if there is a simple way to transform it to Json representation like this:
{
"transaction_id": "120",
"transaction_shortname": "120. AUTO"
}
After that i can do the following to get a Transaction object:
JObject j = JObject.Parse("{\"transaction_id\": \"120\",\"transaction_shortname\": \"120. AUTO\"}");
transaction ttttt = JsonConvert.DeserializeObject<transaction>(j.ToString());
No, this can't be converted to JSON automatically, you need to parse the format you have manually. And I don't know any language which supports this syntax.
However, if you're absolutely sure there won't be some complex cases like quoted strings and "=" and "\"" in values, you can just apply regex:
Regex.Replace(
source.Replace("\r\n", "\n"),
#"(\n\s*)([^\n]*?)\s*=\s*([^\n]*?)([,\n])",
"$1\"$2\": \"$3\"$4")
The excerpt you've given qualifies as HJSON, and so can be parsed by any HJSON library. https://hjson.org/
Thanks for your response,
Lets say i have an object
object j ;
it's base is
{
transaction_id = 120,
transaction_shortname = 120. AUTO
}
I ended by doing the following :
transaction t = JsonConvert.DeserializeObject<transaction>(JsonConvert.SerializeObject(j));

Deserialize json string that contains singlequote using c#

I have a json string that contains a string literal as value of one of the object - PostData.
string json = "{\"PostData\": '{\"LastName\": \"O Corner\",\"FirstName\":\"Mark\",\"Address\":\"123 James St\"}'}";
I am trying to deserialize the json using:
var obj = JsonConvert.DeserializeObject<dynamic>(json);
then, I can use my json string value of PostData like:
obj["PostData"].ToString()
But, as soon as I get the data with single quotes in it, like:
string json = "{\"PostData\": '{\"LastName\": \"O' Corner\",\"FirstName\":\"Mark\",\"Address\":\"123 James St\"}'}";
I get exception on deserialization. How can I escape the single quote?
I have checked SO for similar issues but didn't get any thing working. I also tried one of the solution mentioned int his thread:
JsonSerializerSettings settings = new JsonSerializerSettings
{
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
JsonConvert.SerializeObject(obj, settings);
But, I get Newtonsoft doesnot contain defination for StringEscapeHandling.
Also, tried to escape the singlequote with in the string with \:
'{\"LastName\": \"O\' Corner\",\"FirstName\":\"Mark\",\"Address\":\"123 James St\"}' which didn't work either.
For a start, it might be worth noting that the JSON syntax uses single quotes where you have used double quotes. Here is a guide for proper syntax:
Now unfortunately JSON does not allow the use of single quotes like that, but we can use the unicode \u0027 for an apostrophe and make use of JSON's serializer settings, as you have already done. So your original string:
string json = "{\"PostData\": '{\"LastName\": \"O' Corner\",\"FirstName\":\"Mark\",\"Address\":\"123 James St\"}'}";
becomes:
string json = "{'PostData': {'LastName': 'O\u0027 Corner','FirstName':'Mark','Address':'123 James St'}}"
This is assuming that you are parsing a string literal, otherwise you would need to escape the unicode to give:
string json = "{'PostData': {'LastName': 'O\\u0027 Corner','FirstName':'Mark','Address':'123 James St'}}"

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

How to extract a particular value from a string in c#

I have a string which stores the output of a webservices response in JSON form. in this string I want to get the INI value, it will be either true or false. I just want to get the INI value how to extract the value from the string below in c#
string a= {"active":"true","firstName":"stac","lastName":"Over","INI":"true","userID":"0"}
Don't reinvent the wheel, use the built-in JavaScriptSerializer:
var serializer = new JavaScriptSerializer();
var dictionary = (IDictionary<string, object>)serializer.DeserializeObject(a);
string ini = (string)dictionary["INI"];
The response that you get is a JSONObject. One approach is to take your response and use a JSON library to parse out the values. Like Thomas' answer above, you'll be able to treat it like a dictionary and given a key, "INI", get the value from your response object.
Cheers.

Categories