string result="12334,23432,3453455";
I am getting this string through Ajax call but it gives me the following error:
"unexpected non-whitespace character after JSON data"
When I remove comma's between strings it works fine .How to handle this?. I want to put value in textarea with comma's after the Ajax call
Whatever's outputting that isn't doing so in JSON format, but more like CSV.
A few options:
If you're able, fix the output method to correctly output JSON
Parse the string like a CSV
e.g. "12334,23432,3453455".split(',')
Conform the output to JSON first, then parse
e.g. JSON.parse("["+"12334,23432,3453455"+"]") (wrap with [])
Specify dataType:'text' in your $.ajax call.
Options 1-3 of the above would result in [12334,23432,3453455] as a javascript array of numbers, while Option 4 will simply result in "12334,23432,3453455" as a string.
BTW, using JSON.NET, this is what it should result in:
// As an array:
Int32[] ary = new[]{ 12334, 23432, 3453455 };
Console.WriteLine(JsonConvert.SerializeObject(ary));
// [12334,23432,3453455]
// As a string:
String str = "12334,23432,3453455";
Console.WriteLine(JsonConvert.SerializeObject(str));
// "12334,23432,3453455"
Your data has to be parsed by your JSON parser.
If your data is an array, your string should look like:
"[12334,23432,3453455]"
or should it be astring:
"\"12334,23432,3453455\""
Related
I want to pass a filepath through JSON. On deserializing I am getting error:
Unrecognized escape sequence. (43): {"Jobtype": "StepBatch","SelectedId": "D:\Input\file1.CATPart"}
I have escaped characters but it still shows error...am I missing something here?
string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\Input\\file1.CATPart\"}";
var jsonObj = new JavaScriptSerializer().Deserialize<List<Arguments>>(json);
The problem is that the content of your string at execution time is:
{"Jobtype": "StepBatch","SelectedId": "D:\Input\file1.CATPart"}
That's not valid JSON, because of the backslashes in the value for SelectedId. You'd need the JSON to be:
{"Jobtype": "StepBatch","SelectedId": "D:\\Input\\file1.CATPart"}
so your C# would have to be:
string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\\\Input\\\\file1.CATPart\"}";
However, given that you're immediately deserializing the JSON anyway, I'd suggest getting rid of the JSON part entirely, and just creating the Arguments values yourself.
If you need to produce JSON, create the right values directly, and then get JavaScriptSerializer (or preferrably Json.NET) to create the JSON for you, instead of hand-coding it.
Dears
I have a byte array that is returned from web server , it is a part of json-serialized object (property value)
It looks like below in the json string:
,"n":"y1GpP7FibyTYl40Jhx1B90WOi1mecJfpi4IEhbHPbAB64jhV16UlpEPyGpNIzDS4Lct80sIs7FW5Vnf38Z-tzPbtHyFVYYU2AC4SVrwQp9-ELz-..._xW3bmMxuwoBgHpWDTw"
Please note that there is no double equal sign at the end, like for Base64 strings. I've used three dots (...) to make string representation a little bit shorter
I can deserialize object and get proper byte array:
var kb = JsonConvert.DeserializeObject<KeyBundle>(Properties.Resources.keyBundleJson);
And can it serialize to json back:
JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.None,
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(kb, settings);
But the problem is that result property value looks not the same as original string:
from web server it was:
y1GpP7FibyTYl40Jhx1B90WOi1mecJfpi4IEhbHPbAB64jhV16UlpEPyGpNIzDS4Lct80sIs7FW5Vnf38Z-tzPbtHyFVYYU2AC4SVrwQp9-ELz-..._xW3bmMxuwoBgHpWDTw
serialized locally:
y1GpP7FibyTYl40Jhx1B90WOi1mecJfpi4IEhbHPbAB64jhV16UlpEPyGpNIzDS4Lct80sIs7FW5Vnf38Z+tzPbtHyFVYYU2AC4SVrwQp9+ELz+.../xW3bmMxuwoBgHpWDTw==
underscores and slashes, plus and minus signs, two equal signs at the end
is it possible to serialize byte array exactly as it is done by web-server?
I have an idea to serialize it with Json and then replace minus with plus, underscore with slash and remove last two equal signs.
Any other method to get it immediately out of the box?
Regards
In urls there is different variant of Base64 used with - and _ which doesn't require additional encoding (e.g. + would be encoded to %2B). For this you can simply use string Replace method to replace those characters.
If you want an out-of-the box solution you can try Microsoft.IdentityModel.Tokens nuget package:
var encoded = Base64UrlEncoder.Encode(someString);
var decoded = Base64UrlEncoder.Decode(encoded);
For more info: https://en.wikipedia.org/wiki/Base64#URL_applications
I have an long JSON that include array.
All the JSON is dynamic and i don't have const structure to this JSON.
Only i know is that "JSON" include this array.
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
I want with c# extract an array of the first name from this .
I tried to do that but not succeed.
use json.net. Deserialize to dynamic.
dynamic x = JsonConvert.DeserialzeObject(jsonStr);
What I normally do is split the JSON string using the C# native String.Split
const string quote = "\""; //You can ignore this line if you like it just adds the "" as a constant string/char value!
string storedValue = "{"firstName":"John", "lastName":"Doe"}" //The JSON value stored either from an HTTPWebRequest or some other method!
string[] str = storedValue.Split(new string[] {quote + "firstName" + quote + ":" }, StringSplitOptions.None); //Split the JSON firstName value!
So the compiler would essentially look for "firstName": and split the firstName value with all the other code, but then if you did str[1] it would also grab lastName value so what I always do after sending the HTTPWebRequest to receive the Request from the target server, and I split the ID I want I then split one final time at the "," to remove last name from the JSON code I want to spit!
string[] finalSplit = str.Split(new string[] { "," }, StringSplitOptions.None);
string output = finalSplit[0].ToString();
as far as I can tell the 'output' string value should equal the "John" value from your JSON code!
If you want to remove the quotes use the Regex.Replace() in C#.
using System.Net.RegularExpressions; //Import C# library using this code at the top of your class or above the Namespace declaration!
Regex.Replace(output, #quotes, ""); //The 'quotes' method was declared at the top of the first code block it was that code I said you could ignore if you really wanted to!
after removing the quotes the last thing to do is just place output into a label, textbox, or maybe even a file using System.IO.streamWriter!
Also btw how where you getting the JSON code from a file or VIA an HTTPWebRequest? If you are getting the JSON code from an HTTPWebRequest I recommend converting the code to UTF-8 just to be on the safe side!
Now I know there is a more official way to read JSON in C# but this is MY method and it works for me so I see no reason in using an official method if I have one that works just as well, but again this is just my opinion! :)
I have a c# program that retrieve some JSON data and use Newtonsoft JSON to Deserialize it.
as i use persian chars in my program the JSON codes will be shown like this:\u060c \u067e\u0644\u0627\u06a9 .... also after i retrive the JSON data in my program this chars still show like its coded sample.but after i Deserialize it converted to ???? chars.
what should i do?
Your JSON deserializer is broken; \uXXXX is supposed to be turned into proper characters.
To do that yourself, use this function
// Turns every occurrence of \uXXXX into a proper character
void UnencodeJSONUnicode(string str) {
return Regex.Replace(str,
#"\\u(?<value>[0-9a-f]{4})",
match => {
string digits = match.Groups["value"].Value;
int number = int.Parse(digits, NumberStyles.HexNumber);
return char.ConvertFromUtf32(number);
});
}
(Untested code; I don't have VS available at the moment. Some exception handling would probably be nice too)
Looks like it has been JSON encoded, so you need to decode it. The DataContractJsonSerializer class can do this.
See this MSDN link for more information.
I'll parse http://www.finam.ru/scripts/export.js
Since that javascript data looks like comma seperated values, just remove javascript stuff like
leading var aEmitentIds=new Array( and
trailing );
and use csv library to parse the data.