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*)",")");
Related
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
Following interpolated string formation works well:
string BG="7263-2323";
string PG="2983-2323";
string interpolatedString = $"{BG};{PG}";
Console.WriteLine(interpolatedString);
Result in variable interpolatedString:
7263-2323;2983-2323
But, the problem is that I store interpolatedString in database, then it does not display values for BG and PG... Instead it displays string as it is:
$\"{BG};{PG}\"
How can I solve this issue? Any idea?
You can't do that. Interpolated strings are effectively just syntactic sugar for using string.Format. Instead you would need to store your strings like this:
Hello {0}, welcome to my app
And then use string.Format:
var format = "Hello {0}, welcome to my app";
var output = string.format(format, "Bob");
Alternatively you could roll your own, for example:
var format = "Hello {name}, welcome to my app";
var output = format.Replace("{name}", "Bob");
Note that my example here isn't particularly efficient so you may want to use something like StringBuilder if you're doing a lot of this.
I have this json string passed to my webapi
string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";
I may have more than on pair of (K,V) inside. How do i parse this in C# ?
I thought i could first convert my string to a JObject and get the key for datamodel from that and then use JArray to parse the K,V. But its throwing a jsonreader exception on the first line of code here
JObject my_obj = JsonConvert.DeserializeObject<JObject>(jsonstring.ToString());
and then do this..
JObject data = my_obj["datamodel"].Value<JObject>();
First of all, the JSON string you are posting is not valid. Given your comment, you can clean up the quotes before and after the square brackets using this snippet:
string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";;
string jsonstringCleaned = jsonstring.Replace("\"[", "[").Replace("]\"", "]");
var my_obj = JsonConvert.DeserializeObject<JObject>(jsonstringCleaned);
The code is right, but the exception you are getting is related to the formatting of your JSON string. If you put valid JSON in this code, it should work as expected.
There are \" missing around V1 in your JSON string.
It should look like this:
string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";
First always make sure that you have a valid Json string. A simple way to do that is paste it into a Json to C# converter tool, such as this one: http://json2csharp.com/
It may be simpler and more readable to use single quotes within your Json string if that is an option, as it avoids the need to escape the double quotes:
string jsonstring = "{'datamodel': [{'K1':'V1','K2':'V2'}]}"
Now we deserialize the object and get the JArray. There is no need to call the ToString() on the JSON jsonstring string.
var my_obj = JsonConvert.DeserializeObject<JObject>(jsonstring);
var data = (JArray)my_obj["datamodel"];
A better and more concise way to accomplish the same result could be to just use JObject.Parse. We can accomplish the same result with just one line of code.
var data = (JArray)JObject.Parse(jsonstring)["datamodel"];
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'}}"
I'm trying to use System.Text.RegularExpressions.Regex class to grab some text from a JSON string. The sting is something like
[{"name":"joe","message":"hello","sent":"datetime"}{"name":"steve","message":"bye","sent":"datetime"}]
I'm attempting to use the Matches() method to grab the "message" values. However, specifying a match as something like message":"*","sent as the pattern would return 3 matches:
hello
bye
hello","sent":"datetime"}{"name":"steve","message":"bye
How do I structure the options or modify my pattern to exclude recursive regex checks? I only want matches
hello
bye
The JavaScriptSerializer class (namespace System.Web.Script.Serialization, assembly System.Web.Extensions.dll) is pretty useful for dealing with JSON strings like this.
var json = "[{\"name\":\"joe\",\"message\":\"hello\",\"sent\":\"datetime\"},{\"name\":\"steve\",\"message\":\"bye\",\"sent\":\"datetime\"}]";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<object[]>(json);
// now have an array of objects, each of which happens to be an IDictionary<string, object>
foreach(IDictionary<string, object> map in result)
{
var messageValue = map["message"].ToString();
Console.WriteLine("message = {0}", messageValue);
}
JSON is better parsed by a JSON tool.
You can try using the non-greedy syntax .*? for example.