Json get array object from JSON Object C# - c#

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"];

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);

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

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'}}"

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"
}
}

Categories