Can't parse json from Resources - c#

In resources I have json file with next content:
{
"EU": [
"Germany",
"Ukraine",
"United Kingdom",
"Hungary"
]
}
I want to deserialize it into Dictionary<string,List<string>>
I've tried next :
var json = Encoding.UTF8.GetString(Resources.regionGroups);//Resources.regionGroups return byte[]
return JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(json);
But every time I get exception as variable json is in incorect json format.
What can cause this? I've tried the same deserialization but with jsonString as hard-coded and it works.
Detailed exception message :
Unexpected character encountered while parsing value: . Path '', line
0, position 0.
UPDATE :
After removing all spaces
var json = Regex.Replace(Encoding.UTF8.GetString(Resources.regionGroups), "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1");
from string I have next one
"{\"EU\":[\"Germany\",\"Ukraine\",\"United Kingdom\",\"Hungary\"]}"
which also reproduce exception.

Well #AmitKumarGhosh was right about encoding, as I think.
So I've tried to change type of my json file in the Resources. I've changed it from binary to text file and this helps.
So parsing now is very simple :
JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(Resources.regionGroups);

Related

When deserializing Json string that contains "\" gives Bad Json escape sequence

I have a input field in UI which contains a field Value with "\\test\a\b\c". The Json string in API after serialization has the Value field as below.
{
"ItemKey": "8b603493-3d2d-4903-a054-2abb895ab870",
"ParentKey": "00000000-0000-0000-0000-000000000000",
"Schema": "",
"SchemaTypeName": "",
"Value": "\\\\test\\a\\b\\c",
"ValueDefinition": null
}
When deserializing this string I get the error,
var result = JsonConvert.DeserializeObject<Class>(rootElement);
{"Bad JSON escape sequence: \\M. Path 'sample[0].sample[1].Value', line 1, position 3384."}
I tried double escaping "\" and this error is resolved.
var tempStr = valueReplacement.Replace(#"\\", #"\").Replace(#"//", #"/");
valueReplacement = tempStr.Replace(#"\", #"\\").Replace(#"/", #"//");
{"Value": "\\test\\a\\b\\c"}
But I need the final json that is generated after deserializing to have the value still the same because I need to integrate this with UI.
"Value": "\\test\a\b\c"
Is there any way I can change the value again after deserialization?

Having error upon trying to parse a JSON array into JSON object

I am trying to parse a JSON array by using this code:
public async Task QuoteAsync()
{
await this.Context.Channel.TriggerTypingAsync();
var client = new HttpClient();
var result = await client.GetStringAsync("https://zenquotes.io/api/random");
JArray qarray = JArray.Parse(result);
JObject quote = JObject.Parse(qarray[0]["q"].ToString());
JObject author = JObject.Parse(qarray[0]["a"].ToString());
await this.ReplyAsync($"{quote} - {author}");
}
The response I receive upon sending a request to zenquotes api is
[
{
"q": "Be where your enemy is not.",
"a": "Sun Tzu",
"h": "<blockquote>“Be where your enemy is not.” — <footer>Sun Tzu</footer></blockquote>"
}
]
I can't seem to figure out why the error is occurring since I don't really see any issues.
This is the error I am getting:
Unexpected character encountered while parsing value: A. Path '', line 0, position 0.
The error is occurring on the 7th line:
JObject quote = JObject.Parse(qarray[0]["q"].ToString());
and since the 8th line is the same I expect the same error.
According to JObject.Parse,
Load a JObject from a string that contains JSON.
For your "q" and "a", it is just a simple string but not a JSON string. Hence you should not use JObject.Parse.
With .ToString(), it is good enough to retrieve the value of q and a.
string quote = qarray[0]["q"].ToString();
string author = qarray[0]["a"].ToString();
Sample program

Does C# have API that removes escaped JSON string?

I have a program where I receive JSON from a server of the format:
{
"Parent1Key":"{\n \"Child11Key\" : 0,\n \"Child21Key\" : \"successfully.\"\n}\n",
"Parent2Key":"{\n \"child21\" : true,\n \"Child22\" : \"successful.\"\n}\n"
}
This string is manually escaped in our program to be of the format:
{"Parent1Key":{ "Child11Key" : 0, "Child21Key" : "successfully." },"Parent2Key":{ "child21" : true, "Child22" : "successful." }}
Sorry, the specific code to make this change cannot be shared in this question.
so that we can pass it to our deserialize logic.
We are getting problem when we save strings with escaped characters like when "child22" : "{text", or "child22" : "text}".
Is there a C# API that removes the escaped JSON formatting correctly and returns the required string.
So it seems like you have some JSON which has been constructed by serializing some objects (Parent1Key and Parent2Key), then taking those serialized strings, adding them to another object and serializing that. So the inner objects end up double-serialized.
What you need to do is reverse that process by re-parsing the inner objects. You can do that using Json.Net:
JObject obj = JObject.Parse(json);
obj["Parent1Key"] = JObject.Parse((string)obj["Parent1Key"]);
obj["Parent2Key"] = JObject.Parse((string)obj["Parent2Key"]);
json = obj.ToString();
Fiddle: https://dotnetfiddle.net/z2zpd5

Why is this Json.Net conversion from XML and JSON not working?

You can enter either of these URLs into a browser and verify that they return valid xml:
http://maps.googleapis.com/maps/api/geocode/xml?`address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false"
...or json:
http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false%22
...but when attempting to get the xml programmatically using this code (after installing Json.NET via NuGet into my project and dropping a dataGridView on my Windows form):
dataGridView1.DataSource = GetLocationData("http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false");
private JArray GetLocationData(string uri)
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
return JsonConvert.DeserializeObject<JArray>(s);
}
...I get:
Newtonsoft.Json.JsonReaderException was unhandled
_message=Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
I thought, okay, this actually is json code, not xml, so I replaced "xml" with "json" in the URL, expecting more joy in Mudville.
However, when attempting to get the same data as json, I also get an exception, namely, "System.InvalidCastException was unhandled _message=Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'."
Why, and how can I fix it? Is it possible to also grab the data as xml?
Using the json URL is correct. Your problem is that the JSON response is not giving you an array which is your error.
Notice that the response you get back is an object denoted by the {
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
....
If it was an array, you would get back [ instead. You should use JObject or a custom model instead of JArray. The results element is what contains the actual array that you will need to loop through.
Pseudo for the result you are actually getting in the response:
object
{
Result[] results;
string status;
}
You can also grab the XML version if you want, but then you need to actually have an object model defined to match and use the XmlSerializer to deserialize it or load it into an XmlDocument (lots of ways to work with XML). However, you cannot pass XML into the JSON serializer as it is expecting a JSON string.
EDIT:
There are methods on JsonConvert to convert from XML. See this answer here: How to convert JSON to XML or XML to JSON?

Regex to replace JSON structure

I have JSON text like this :
...
"simples":{
"AS100ELABQVKANID-91057":{
"meta":{
"sku":"AS100ELABQVKANID-91057",
"price":"3669000.00",
"original_price":"3379000.00",
"special_to_date":"2015-03-19 23:59:59",
"shipment_type":"1",
"special_price":"3299000.00",
"tax_percent":"10.00",
"sourceability":"Sourceable",
"quantity":"15",
"variation":"...",
"package_type_position":"0",
"min_delivery_time":"1",
"max_delivery_time":"3",
"attribute_set_name":"electronics",
"3hours_shipment_available":false,
"estimated_delivery":"",
"estimated_delivery_position":""
},
"attributes":{
"package_type":"Parcel"
}
}
},
"description":
...
The above text appears repeatedly in my JSON text. I am trying to build every result to this :
"simples":[],"description"
So far, I have made this regex :
\"simples\":{(?:.*v(?:|=)|(?:.*)?)},\"description\"
But the result is cut everything from my first "simples" into last "description".
Regex newbie here.
Thanks in advance
I recommend parsing the JSON, replacing the value, then re-stringifying it
var obj = JSON.parse(json);
obj.simples = [];
json = JSON.stringify(obj);
Using a regexp for this is pure insanity
Don't use Regex to parse JSON; use a JSON parser.
Here is how you can do this using JSON.Net, assuming the object containing simples is part of a flat list of results:
JArray array = JArray.Parse(json);
foreach (JObject obj in array)
{
obj["simples"].Parent.Remove();
}
json = array.ToString();
If your JSON is more complicated (i.e. "simples" can appear at more than one level in the JSON), then you will need a recursive search to find and remove it. This answer has a helper method that can find a specific property by name anywhere in the JSON and return a list of all occurrences. Once you have the list of occurrences, you can then loop through them and remove them as shown above.

Categories

Resources